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 "TestInterfaces.h"
12 #include "TestTypes.h"
13 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
14 #include "mlir/Dialect/DLTI/DLTI.h"
15 #include "mlir/Dialect/StandardOps/IR/Ops.h"
16 #include "mlir/Dialect/Tensor/IR/Tensor.h"
17 #include "mlir/IR/BuiltinOps.h"
18 #include "mlir/IR/DialectImplementation.h"
19 #include "mlir/IR/PatternMatch.h"
20 #include "mlir/IR/TypeUtilities.h"
21 #include "mlir/Reducer/ReductionPatternInterface.h"
22 #include "mlir/Transforms/FoldUtils.h"
23 #include "mlir/Transforms/InliningUtils.h"
24 #include "llvm/ADT/StringSwitch.h"
25 
26 // Include this before the using namespace lines below to
27 // test that we don't have namespace dependencies.
28 #include "TestOpsDialect.cpp.inc"
29 
30 using namespace mlir;
31 using namespace test;
32 
33 void test::registerTestDialect(DialectRegistry &registry) {
34   registry.insert<TestDialect>();
35 }
36 
37 //===----------------------------------------------------------------------===//
38 // TestDialect Interfaces
39 //===----------------------------------------------------------------------===//
40 
41 namespace {
42 
43 /// Testing the correctness of some traits.
44 static_assert(
45     llvm::is_detected<OpTrait::has_implicit_terminator_t,
46                       SingleBlockImplicitTerminatorOp>::value,
47     "has_implicit_terminator_t does not match SingleBlockImplicitTerminatorOp");
48 static_assert(OpTrait::hasSingleBlockImplicitTerminator<
49                   SingleBlockImplicitTerminatorOp>::value,
50               "hasSingleBlockImplicitTerminator does not match "
51               "SingleBlockImplicitTerminatorOp");
52 
53 // Test support for interacting with the AsmPrinter.
54 struct TestOpAsmInterface : public OpAsmDialectInterface {
55   using OpAsmDialectInterface::OpAsmDialectInterface;
56 
57   AliasResult getAlias(Attribute attr, raw_ostream &os) const final {
58     StringAttr strAttr = attr.dyn_cast<StringAttr>();
59     if (!strAttr)
60       return AliasResult::NoAlias;
61 
62     // Check the contents of the string attribute to see what the test alias
63     // should be named.
64     Optional<StringRef> aliasName =
65         StringSwitch<Optional<StringRef>>(strAttr.getValue())
66             .Case("alias_test:dot_in_name", StringRef("test.alias"))
67             .Case("alias_test:trailing_digit", StringRef("test_alias0"))
68             .Case("alias_test:prefixed_digit", StringRef("0_test_alias"))
69             .Case("alias_test:sanitize_conflict_a",
70                   StringRef("test_alias_conflict0"))
71             .Case("alias_test:sanitize_conflict_b",
72                   StringRef("test_alias_conflict0_"))
73             .Case("alias_test:tensor_encoding", StringRef("test_encoding"))
74             .Default(llvm::None);
75     if (!aliasName)
76       return AliasResult::NoAlias;
77 
78     os << *aliasName;
79     return AliasResult::FinalAlias;
80   }
81 
82   AliasResult getAlias(Type type, raw_ostream &os) const final {
83     if (auto tupleType = type.dyn_cast<TupleType>()) {
84       if (tupleType.size() > 0 &&
85           llvm::all_of(tupleType.getTypes(), [](Type elemType) {
86             return elemType.isa<SimpleAType>();
87           })) {
88         os << "test_tuple";
89         return AliasResult::FinalAlias;
90       }
91     }
92     if (auto intType = type.dyn_cast<TestIntegerType>()) {
93       if (intType.getSignedness() ==
94               TestIntegerType::SignednessSemantics::Unsigned &&
95           intType.getWidth() == 8) {
96         os << "test_ui8";
97         return AliasResult::FinalAlias;
98       }
99     }
100     return AliasResult::NoAlias;
101   }
102 };
103 
104 struct TestDialectFoldInterface : public DialectFoldInterface {
105   using DialectFoldInterface::DialectFoldInterface;
106 
107   /// Registered hook to check if the given region, which is attached to an
108   /// operation that is *not* isolated from above, should be used when
109   /// materializing constants.
110   bool shouldMaterializeInto(Region *region) const final {
111     // If this is a one region operation, then insert into it.
112     return isa<OneRegionOp>(region->getParentOp());
113   }
114 };
115 
116 /// This class defines the interface for handling inlining with standard
117 /// operations.
118 struct TestInlinerInterface : public DialectInlinerInterface {
119   using DialectInlinerInterface::DialectInlinerInterface;
120 
121   //===--------------------------------------------------------------------===//
122   // Analysis Hooks
123   //===--------------------------------------------------------------------===//
124 
125   bool isLegalToInline(Operation *call, Operation *callable,
126                        bool wouldBeCloned) const final {
127     // Don't allow inlining calls that are marked `noinline`.
128     return !call->hasAttr("noinline");
129   }
130   bool isLegalToInline(Region *, Region *, bool,
131                        BlockAndValueMapping &) const final {
132     // Inlining into test dialect regions is legal.
133     return true;
134   }
135   bool isLegalToInline(Operation *, Region *, bool,
136                        BlockAndValueMapping &) const final {
137     return true;
138   }
139 
140   bool shouldAnalyzeRecursively(Operation *op) const final {
141     // Analyze recursively if this is not a functional region operation, it
142     // froms a separate functional scope.
143     return !isa<FunctionalRegionOp>(op);
144   }
145 
146   //===--------------------------------------------------------------------===//
147   // Transformation Hooks
148   //===--------------------------------------------------------------------===//
149 
150   /// Handle the given inlined terminator by replacing it with a new operation
151   /// as necessary.
152   void handleTerminator(Operation *op,
153                         ArrayRef<Value> valuesToRepl) const final {
154     // Only handle "test.return" here.
155     auto returnOp = dyn_cast<TestReturnOp>(op);
156     if (!returnOp)
157       return;
158 
159     // Replace the values directly with the return operands.
160     assert(returnOp.getNumOperands() == valuesToRepl.size());
161     for (const auto &it : llvm::enumerate(returnOp.getOperands()))
162       valuesToRepl[it.index()].replaceAllUsesWith(it.value());
163   }
164 
165   /// Attempt to materialize a conversion for a type mismatch between a call
166   /// from this dialect, and a callable region. This method should generate an
167   /// operation that takes 'input' as the only operand, and produces a single
168   /// result of 'resultType'. If a conversion can not be generated, nullptr
169   /// should be returned.
170   Operation *materializeCallConversion(OpBuilder &builder, Value input,
171                                        Type resultType,
172                                        Location conversionLoc) const final {
173     // Only allow conversion for i16/i32 types.
174     if (!(resultType.isSignlessInteger(16) ||
175           resultType.isSignlessInteger(32)) ||
176         !(input.getType().isSignlessInteger(16) ||
177           input.getType().isSignlessInteger(32)))
178       return nullptr;
179     return builder.create<TestCastOp>(conversionLoc, resultType, input);
180   }
181 
182   void processInlinedCallBlocks(
183       Operation *call,
184       iterator_range<Region::iterator> inlinedBlocks) const final {
185     if (!isa<ConversionCallOp>(call))
186       return;
187 
188     // Set attributed on all ops in the inlined blocks.
189     for (Block &block : inlinedBlocks) {
190       block.walk([&](Operation *op) {
191         op->setAttr("inlined_conversion", UnitAttr::get(call->getContext()));
192       });
193     }
194   }
195 };
196 
197 struct TestReductionPatternInterface : public DialectReductionPatternInterface {
198 public:
199   TestReductionPatternInterface(Dialect *dialect)
200       : DialectReductionPatternInterface(dialect) {}
201 
202   void populateReductionPatterns(RewritePatternSet &patterns) const final {
203     populateTestReductionPatterns(patterns);
204   }
205 };
206 
207 } // namespace
208 
209 //===----------------------------------------------------------------------===//
210 // TestDialect
211 //===----------------------------------------------------------------------===//
212 
213 static void testSideEffectOpGetEffect(
214     Operation *op,
215     SmallVectorImpl<SideEffects::EffectInstance<TestEffects::Effect>> &effects);
216 
217 // This is the implementation of a dialect fallback for `TestEffectOpInterface`.
218 struct TestOpEffectInterfaceFallback
219     : public TestEffectOpInterface::FallbackModel<
220           TestOpEffectInterfaceFallback> {
221   static bool classof(Operation *op) {
222     bool isSupportedOp =
223         op->getName().getStringRef() == "test.unregistered_side_effect_op";
224     assert(isSupportedOp && "Unexpected dispatch");
225     return isSupportedOp;
226   }
227 
228   void
229   getEffects(Operation *op,
230              SmallVectorImpl<SideEffects::EffectInstance<TestEffects::Effect>>
231                  &effects) const {
232     testSideEffectOpGetEffect(op, effects);
233   }
234 };
235 
236 void TestDialect::initialize() {
237   registerAttributes();
238   registerTypes();
239   addOperations<
240 #define GET_OP_LIST
241 #include "TestOps.cpp.inc"
242       >();
243   addInterfaces<TestOpAsmInterface, TestDialectFoldInterface,
244                 TestInlinerInterface, TestReductionPatternInterface>();
245   allowUnknownOperations();
246 
247   // Instantiate our fallback op interface that we'll use on specific
248   // unregistered op.
249   fallbackEffectOpInterfaces = new TestOpEffectInterfaceFallback;
250 }
251 TestDialect::~TestDialect() {
252   delete static_cast<TestOpEffectInterfaceFallback *>(
253       fallbackEffectOpInterfaces);
254 }
255 
256 Operation *TestDialect::materializeConstant(OpBuilder &builder, Attribute value,
257                                             Type type, Location loc) {
258   return builder.create<TestOpConstant>(loc, type, value);
259 }
260 
261 ::mlir::LogicalResult FormatInferType2Op::inferReturnTypes(
262     ::mlir::MLIRContext *context, ::llvm::Optional<::mlir::Location> location,
263     ::mlir::ValueRange operands, ::mlir::DictionaryAttr attributes,
264     ::mlir::RegionRange regions,
265     ::llvm::SmallVectorImpl<::mlir::Type> &inferredReturnTypes) {
266   inferredReturnTypes.assign({::mlir::IntegerType::get(context, 16)});
267   return ::mlir::success();
268 }
269 
270 void *TestDialect::getRegisteredInterfaceForOp(TypeID typeID,
271                                                OperationName opName) {
272   if (opName.getIdentifier() == "test.unregistered_side_effect_op" &&
273       typeID == TypeID::get<TestEffectOpInterface>())
274     return fallbackEffectOpInterfaces;
275   return nullptr;
276 }
277 
278 LogicalResult TestDialect::verifyOperationAttribute(Operation *op,
279                                                     NamedAttribute namedAttr) {
280   if (namedAttr.getName() == "test.invalid_attr")
281     return op->emitError() << "invalid to use 'test.invalid_attr'";
282   return success();
283 }
284 
285 LogicalResult TestDialect::verifyRegionArgAttribute(Operation *op,
286                                                     unsigned regionIndex,
287                                                     unsigned argIndex,
288                                                     NamedAttribute namedAttr) {
289   if (namedAttr.getName() == "test.invalid_attr")
290     return op->emitError() << "invalid to use 'test.invalid_attr'";
291   return success();
292 }
293 
294 LogicalResult
295 TestDialect::verifyRegionResultAttribute(Operation *op, unsigned regionIndex,
296                                          unsigned resultIndex,
297                                          NamedAttribute namedAttr) {
298   if (namedAttr.getName() == "test.invalid_attr")
299     return op->emitError() << "invalid to use 'test.invalid_attr'";
300   return success();
301 }
302 
303 Optional<Dialect::ParseOpHook>
304 TestDialect::getParseOperationHook(StringRef opName) const {
305   if (opName == "test.dialect_custom_printer") {
306     return ParseOpHook{[](OpAsmParser &parser, OperationState &state) {
307       return parser.parseKeyword("custom_format");
308     }};
309   }
310   if (opName == "test.dialect_custom_format_fallback") {
311     return ParseOpHook{[](OpAsmParser &parser, OperationState &state) {
312       return parser.parseKeyword("custom_format_fallback");
313     }};
314   }
315   return None;
316 }
317 
318 llvm::unique_function<void(Operation *, OpAsmPrinter &)>
319 TestDialect::getOperationPrinter(Operation *op) const {
320   StringRef opName = op->getName().getStringRef();
321   if (opName == "test.dialect_custom_printer") {
322     return [](Operation *op, OpAsmPrinter &printer) {
323       printer.getStream() << " custom_format";
324     };
325   }
326   if (opName == "test.dialect_custom_format_fallback") {
327     return [](Operation *op, OpAsmPrinter &printer) {
328       printer.getStream() << " custom_format_fallback";
329     };
330   }
331   return {};
332 }
333 
334 //===----------------------------------------------------------------------===//
335 // TestBranchOp
336 //===----------------------------------------------------------------------===//
337 
338 Optional<MutableOperandRange>
339 TestBranchOp::getMutableSuccessorOperands(unsigned index) {
340   assert(index == 0 && "invalid successor index");
341   return getTargetOperandsMutable();
342 }
343 
344 //===----------------------------------------------------------------------===//
345 // TestDialectCanonicalizerOp
346 //===----------------------------------------------------------------------===//
347 
348 static LogicalResult
349 dialectCanonicalizationPattern(TestDialectCanonicalizerOp op,
350                                PatternRewriter &rewriter) {
351   rewriter.replaceOpWithNewOp<arith::ConstantOp>(
352       op, rewriter.getI32IntegerAttr(42));
353   return success();
354 }
355 
356 void TestDialect::getCanonicalizationPatterns(
357     RewritePatternSet &results) const {
358   results.add(&dialectCanonicalizationPattern);
359 }
360 
361 //===----------------------------------------------------------------------===//
362 // TestFoldToCallOp
363 //===----------------------------------------------------------------------===//
364 
365 namespace {
366 struct FoldToCallOpPattern : public OpRewritePattern<FoldToCallOp> {
367   using OpRewritePattern<FoldToCallOp>::OpRewritePattern;
368 
369   LogicalResult matchAndRewrite(FoldToCallOp op,
370                                 PatternRewriter &rewriter) const override {
371     rewriter.replaceOpWithNewOp<CallOp>(op, TypeRange(), op.getCalleeAttr(),
372                                         ValueRange());
373     return success();
374   }
375 };
376 } // namespace
377 
378 void FoldToCallOp::getCanonicalizationPatterns(RewritePatternSet &results,
379                                                MLIRContext *context) {
380   results.add<FoldToCallOpPattern>(context);
381 }
382 
383 //===----------------------------------------------------------------------===//
384 // Test Format* operations
385 //===----------------------------------------------------------------------===//
386 
387 //===----------------------------------------------------------------------===//
388 // Parsing
389 
390 static ParseResult
391 parseCustomOptionalOperand(OpAsmParser &parser,
392                            Optional<OpAsmParser::OperandType> &optOperand) {
393   if (succeeded(parser.parseOptionalLParen())) {
394     optOperand.emplace();
395     if (parser.parseOperand(*optOperand) || parser.parseRParen())
396       return failure();
397   }
398   return success();
399 }
400 
401 static ParseResult parseCustomDirectiveOperands(
402     OpAsmParser &parser, OpAsmParser::OperandType &operand,
403     Optional<OpAsmParser::OperandType> &optOperand,
404     SmallVectorImpl<OpAsmParser::OperandType> &varOperands) {
405   if (parser.parseOperand(operand))
406     return failure();
407   if (succeeded(parser.parseOptionalComma())) {
408     optOperand.emplace();
409     if (parser.parseOperand(*optOperand))
410       return failure();
411   }
412   if (parser.parseArrow() || parser.parseLParen() ||
413       parser.parseOperandList(varOperands) || parser.parseRParen())
414     return failure();
415   return success();
416 }
417 static ParseResult
418 parseCustomDirectiveResults(OpAsmParser &parser, Type &operandType,
419                             Type &optOperandType,
420                             SmallVectorImpl<Type> &varOperandTypes) {
421   if (parser.parseColon())
422     return failure();
423 
424   if (parser.parseType(operandType))
425     return failure();
426   if (succeeded(parser.parseOptionalComma())) {
427     if (parser.parseType(optOperandType))
428       return failure();
429   }
430   if (parser.parseArrow() || parser.parseLParen() ||
431       parser.parseTypeList(varOperandTypes) || parser.parseRParen())
432     return failure();
433   return success();
434 }
435 static ParseResult
436 parseCustomDirectiveWithTypeRefs(OpAsmParser &parser, Type operandType,
437                                  Type optOperandType,
438                                  const SmallVectorImpl<Type> &varOperandTypes) {
439   if (parser.parseKeyword("type_refs_capture"))
440     return failure();
441 
442   Type operandType2, optOperandType2;
443   SmallVector<Type, 1> varOperandTypes2;
444   if (parseCustomDirectiveResults(parser, operandType2, optOperandType2,
445                                   varOperandTypes2))
446     return failure();
447 
448   if (operandType != operandType2 || optOperandType != optOperandType2 ||
449       varOperandTypes != varOperandTypes2)
450     return failure();
451 
452   return success();
453 }
454 static ParseResult parseCustomDirectiveOperandsAndTypes(
455     OpAsmParser &parser, OpAsmParser::OperandType &operand,
456     Optional<OpAsmParser::OperandType> &optOperand,
457     SmallVectorImpl<OpAsmParser::OperandType> &varOperands, Type &operandType,
458     Type &optOperandType, SmallVectorImpl<Type> &varOperandTypes) {
459   if (parseCustomDirectiveOperands(parser, operand, optOperand, varOperands) ||
460       parseCustomDirectiveResults(parser, operandType, optOperandType,
461                                   varOperandTypes))
462     return failure();
463   return success();
464 }
465 static ParseResult parseCustomDirectiveRegions(
466     OpAsmParser &parser, Region &region,
467     SmallVectorImpl<std::unique_ptr<Region>> &varRegions) {
468   if (parser.parseRegion(region))
469     return failure();
470   if (failed(parser.parseOptionalComma()))
471     return success();
472   std::unique_ptr<Region> varRegion = std::make_unique<Region>();
473   if (parser.parseRegion(*varRegion))
474     return failure();
475   varRegions.emplace_back(std::move(varRegion));
476   return success();
477 }
478 static ParseResult
479 parseCustomDirectiveSuccessors(OpAsmParser &parser, Block *&successor,
480                                SmallVectorImpl<Block *> &varSuccessors) {
481   if (parser.parseSuccessor(successor))
482     return failure();
483   if (failed(parser.parseOptionalComma()))
484     return success();
485   Block *varSuccessor;
486   if (parser.parseSuccessor(varSuccessor))
487     return failure();
488   varSuccessors.append(2, varSuccessor);
489   return success();
490 }
491 static ParseResult parseCustomDirectiveAttributes(OpAsmParser &parser,
492                                                   IntegerAttr &attr,
493                                                   IntegerAttr &optAttr) {
494   if (parser.parseAttribute(attr))
495     return failure();
496   if (succeeded(parser.parseOptionalComma())) {
497     if (parser.parseAttribute(optAttr))
498       return failure();
499   }
500   return success();
501 }
502 
503 static ParseResult parseCustomDirectiveAttrDict(OpAsmParser &parser,
504                                                 NamedAttrList &attrs) {
505   return parser.parseOptionalAttrDict(attrs);
506 }
507 static ParseResult parseCustomDirectiveOptionalOperandRef(
508     OpAsmParser &parser, Optional<OpAsmParser::OperandType> &optOperand) {
509   int64_t operandCount = 0;
510   if (parser.parseInteger(operandCount))
511     return failure();
512   bool expectedOptionalOperand = operandCount == 0;
513   return success(expectedOptionalOperand != optOperand.hasValue());
514 }
515 
516 //===----------------------------------------------------------------------===//
517 // Printing
518 
519 static void printCustomOptionalOperand(OpAsmPrinter &printer, Operation *,
520                                        Value optOperand) {
521   if (optOperand)
522     printer << "(" << optOperand << ") ";
523 }
524 
525 static void printCustomDirectiveOperands(OpAsmPrinter &printer, Operation *,
526                                          Value operand, Value optOperand,
527                                          OperandRange varOperands) {
528   printer << operand;
529   if (optOperand)
530     printer << ", " << optOperand;
531   printer << " -> (" << varOperands << ")";
532 }
533 static void printCustomDirectiveResults(OpAsmPrinter &printer, Operation *,
534                                         Type operandType, Type optOperandType,
535                                         TypeRange varOperandTypes) {
536   printer << " : " << operandType;
537   if (optOperandType)
538     printer << ", " << optOperandType;
539   printer << " -> (" << varOperandTypes << ")";
540 }
541 static void printCustomDirectiveWithTypeRefs(OpAsmPrinter &printer,
542                                              Operation *op, Type operandType,
543                                              Type optOperandType,
544                                              TypeRange varOperandTypes) {
545   printer << " type_refs_capture ";
546   printCustomDirectiveResults(printer, op, operandType, optOperandType,
547                               varOperandTypes);
548 }
549 static void printCustomDirectiveOperandsAndTypes(
550     OpAsmPrinter &printer, Operation *op, Value operand, Value optOperand,
551     OperandRange varOperands, Type operandType, Type optOperandType,
552     TypeRange varOperandTypes) {
553   printCustomDirectiveOperands(printer, op, operand, optOperand, varOperands);
554   printCustomDirectiveResults(printer, op, operandType, optOperandType,
555                               varOperandTypes);
556 }
557 static void printCustomDirectiveRegions(OpAsmPrinter &printer, Operation *,
558                                         Region &region,
559                                         MutableArrayRef<Region> varRegions) {
560   printer.printRegion(region);
561   if (!varRegions.empty()) {
562     printer << ", ";
563     for (Region &region : varRegions)
564       printer.printRegion(region);
565   }
566 }
567 static void printCustomDirectiveSuccessors(OpAsmPrinter &printer, Operation *,
568                                            Block *successor,
569                                            SuccessorRange varSuccessors) {
570   printer << successor;
571   if (!varSuccessors.empty())
572     printer << ", " << varSuccessors.front();
573 }
574 static void printCustomDirectiveAttributes(OpAsmPrinter &printer, Operation *,
575                                            Attribute attribute,
576                                            Attribute optAttribute) {
577   printer << attribute;
578   if (optAttribute)
579     printer << ", " << optAttribute;
580 }
581 
582 static void printCustomDirectiveAttrDict(OpAsmPrinter &printer, Operation *op,
583                                          DictionaryAttr attrs) {
584   printer.printOptionalAttrDict(attrs.getValue());
585 }
586 
587 static void printCustomDirectiveOptionalOperandRef(OpAsmPrinter &printer,
588                                                    Operation *op,
589                                                    Value optOperand) {
590   printer << (optOperand ? "1" : "0");
591 }
592 
593 //===----------------------------------------------------------------------===//
594 // Test IsolatedRegionOp - parse passthrough region arguments.
595 //===----------------------------------------------------------------------===//
596 
597 ParseResult IsolatedRegionOp::parse(OpAsmParser &parser,
598                                     OperationState &result) {
599   OpAsmParser::OperandType argInfo;
600   Type argType = parser.getBuilder().getIndexType();
601 
602   // Parse the input operand.
603   if (parser.parseOperand(argInfo) ||
604       parser.resolveOperand(argInfo, argType, result.operands))
605     return failure();
606 
607   // Parse the body region, and reuse the operand info as the argument info.
608   Region *body = result.addRegion();
609   return parser.parseRegion(*body, argInfo, argType, /*argLocations=*/{},
610                             /*enableNameShadowing=*/true);
611 }
612 
613 void IsolatedRegionOp::print(OpAsmPrinter &p) {
614   p << "test.isolated_region ";
615   p.printOperand(getOperand());
616   p.shadowRegionArgs(getRegion(), getOperand());
617   p << ' ';
618   p.printRegion(getRegion(), /*printEntryBlockArgs=*/false);
619 }
620 
621 //===----------------------------------------------------------------------===//
622 // Test SSACFGRegionOp
623 //===----------------------------------------------------------------------===//
624 
625 RegionKind SSACFGRegionOp::getRegionKind(unsigned index) {
626   return RegionKind::SSACFG;
627 }
628 
629 //===----------------------------------------------------------------------===//
630 // Test GraphRegionOp
631 //===----------------------------------------------------------------------===//
632 
633 ParseResult GraphRegionOp::parse(OpAsmParser &parser, OperationState &result) {
634   // Parse the body region, and reuse the operand info as the argument info.
635   Region *body = result.addRegion();
636   return parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{});
637 }
638 
639 void GraphRegionOp::print(OpAsmPrinter &p) {
640   p << "test.graph_region ";
641   p.printRegion(getRegion(), /*printEntryBlockArgs=*/false);
642 }
643 
644 RegionKind GraphRegionOp::getRegionKind(unsigned index) {
645   return RegionKind::Graph;
646 }
647 
648 //===----------------------------------------------------------------------===//
649 // Test AffineScopeOp
650 //===----------------------------------------------------------------------===//
651 
652 ParseResult AffineScopeOp::parse(OpAsmParser &parser, OperationState &result) {
653   // Parse the body region, and reuse the operand info as the argument info.
654   Region *body = result.addRegion();
655   return parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{});
656 }
657 
658 void AffineScopeOp::print(OpAsmPrinter &p) {
659   p << "test.affine_scope ";
660   p.printRegion(getRegion(), /*printEntryBlockArgs=*/false);
661 }
662 
663 //===----------------------------------------------------------------------===//
664 // Test parser.
665 //===----------------------------------------------------------------------===//
666 
667 ParseResult ParseIntegerLiteralOp::parse(OpAsmParser &parser,
668                                          OperationState &result) {
669   if (parser.parseOptionalColon())
670     return success();
671   uint64_t numResults;
672   if (parser.parseInteger(numResults))
673     return failure();
674 
675   IndexType type = parser.getBuilder().getIndexType();
676   for (unsigned i = 0; i < numResults; ++i)
677     result.addTypes(type);
678   return success();
679 }
680 
681 void ParseIntegerLiteralOp::print(OpAsmPrinter &p) {
682   if (unsigned numResults = getNumResults())
683     p << " : " << numResults;
684 }
685 
686 ParseResult ParseWrappedKeywordOp::parse(OpAsmParser &parser,
687                                          OperationState &result) {
688   StringRef keyword;
689   if (parser.parseKeyword(&keyword))
690     return failure();
691   result.addAttribute("keyword", parser.getBuilder().getStringAttr(keyword));
692   return success();
693 }
694 
695 void ParseWrappedKeywordOp::print(OpAsmPrinter &p) { p << " " << getKeyword(); }
696 
697 //===----------------------------------------------------------------------===//
698 // Test WrapRegionOp - wrapping op exercising `parseGenericOperation()`.
699 
700 ParseResult WrappingRegionOp::parse(OpAsmParser &parser,
701                                     OperationState &result) {
702   if (parser.parseKeyword("wraps"))
703     return failure();
704 
705   // Parse the wrapped op in a region
706   Region &body = *result.addRegion();
707   body.push_back(new Block);
708   Block &block = body.back();
709   Operation *wrappedOp = parser.parseGenericOperation(&block, block.begin());
710   if (!wrappedOp)
711     return failure();
712 
713   // Create a return terminator in the inner region, pass as operand to the
714   // terminator the returned values from the wrapped operation.
715   SmallVector<Value, 8> returnOperands(wrappedOp->getResults());
716   OpBuilder builder(parser.getContext());
717   builder.setInsertionPointToEnd(&block);
718   builder.create<TestReturnOp>(wrappedOp->getLoc(), returnOperands);
719 
720   // Get the results type for the wrapping op from the terminator operands.
721   Operation &returnOp = body.back().back();
722   result.types.append(returnOp.operand_type_begin(),
723                       returnOp.operand_type_end());
724 
725   // Use the location of the wrapped op for the "test.wrapping_region" op.
726   result.location = wrappedOp->getLoc();
727 
728   return success();
729 }
730 
731 void WrappingRegionOp::print(OpAsmPrinter &p) {
732   p << " wraps ";
733   p.printGenericOp(&getRegion().front().front());
734 }
735 
736 //===----------------------------------------------------------------------===//
737 // Test PrettyPrintedRegionOp -  exercising the following parser APIs
738 //   parseGenericOperationAfterOpName
739 //   parseCustomOperationName
740 //===----------------------------------------------------------------------===//
741 
742 ParseResult PrettyPrintedRegionOp::parse(OpAsmParser &parser,
743                                          OperationState &result) {
744 
745   SMLoc loc = parser.getCurrentLocation();
746   Location currLocation = parser.getEncodedSourceLoc(loc);
747 
748   // Parse the operands.
749   SmallVector<OpAsmParser::OperandType, 2> operands;
750   if (parser.parseOperandList(operands))
751     return failure();
752 
753   // Check if we are parsing the pretty-printed version
754   //  test.pretty_printed_region start <inner-op> end : <functional-type>
755   // Else fallback to parsing the "non pretty-printed" version.
756   if (!succeeded(parser.parseOptionalKeyword("start")))
757     return parser.parseGenericOperationAfterOpName(
758         result, llvm::makeArrayRef(operands));
759 
760   FailureOr<OperationName> parseOpNameInfo = parser.parseCustomOperationName();
761   if (failed(parseOpNameInfo))
762     return failure();
763 
764   StringRef innerOpName = parseOpNameInfo->getStringRef();
765 
766   FunctionType opFntype;
767   Optional<Location> explicitLoc;
768   if (parser.parseKeyword("end") || parser.parseColon() ||
769       parser.parseType(opFntype) ||
770       parser.parseOptionalLocationSpecifier(explicitLoc))
771     return failure();
772 
773   // If location of the op is explicitly provided, then use it; Else use
774   // the parser's current location.
775   Location opLoc = explicitLoc.getValueOr(currLocation);
776 
777   // Derive the SSA-values for op's operands.
778   if (parser.resolveOperands(operands, opFntype.getInputs(), loc,
779                              result.operands))
780     return failure();
781 
782   // Add a region for op.
783   Region &region = *result.addRegion();
784 
785   // Create a basic-block inside op's region.
786   Block &block = region.emplaceBlock();
787 
788   // Create and insert an "inner-op" operation in the block.
789   // Just for testing purposes, we can assume that inner op is a binary op with
790   // result and operand types all same as the test-op's first operand.
791   Type innerOpType = opFntype.getInput(0);
792   Value lhs = block.addArgument(innerOpType, opLoc);
793   Value rhs = block.addArgument(innerOpType, opLoc);
794 
795   OpBuilder builder(parser.getBuilder().getContext());
796   builder.setInsertionPointToStart(&block);
797 
798   OperationState innerOpState(opLoc, innerOpName);
799   innerOpState.operands.push_back(lhs);
800   innerOpState.operands.push_back(rhs);
801   innerOpState.addTypes(innerOpType);
802 
803   Operation *innerOp = builder.createOperation(innerOpState);
804 
805   // Insert a return statement in the block returning the inner-op's result.
806   builder.create<TestReturnOp>(innerOp->getLoc(), innerOp->getResults());
807 
808   // Populate the op operation-state with result-type and location.
809   result.addTypes(opFntype.getResults());
810   result.location = innerOp->getLoc();
811 
812   return success();
813 }
814 
815 void PrettyPrintedRegionOp::print(OpAsmPrinter &p) {
816   p << ' ';
817   p.printOperands(getOperands());
818 
819   Operation &innerOp = getRegion().front().front();
820   // Assuming that region has a single non-terminator inner-op, if the inner-op
821   // meets some criteria (which in this case is a simple one  based on the name
822   // of inner-op), then we can print the entire region in a succinct way.
823   // Here we assume that the prototype of "special.op" can be trivially derived
824   // while parsing it back.
825   if (innerOp.getName().getStringRef().equals("special.op")) {
826     p << " start special.op end";
827   } else {
828     p << " (";
829     p.printRegion(getRegion());
830     p << ")";
831   }
832 
833   p << " : ";
834   p.printFunctionalType(*this);
835 }
836 
837 //===----------------------------------------------------------------------===//
838 // Test PolyForOp - parse list of region arguments.
839 //===----------------------------------------------------------------------===//
840 
841 ParseResult PolyForOp::parse(OpAsmParser &parser, OperationState &result) {
842   SmallVector<OpAsmParser::OperandType, 4> ivsInfo;
843   // Parse list of region arguments without a delimiter.
844   if (parser.parseRegionArgumentList(ivsInfo))
845     return failure();
846 
847   // Parse the body region.
848   Region *body = result.addRegion();
849   auto &builder = parser.getBuilder();
850   SmallVector<Type, 4> argTypes(ivsInfo.size(), builder.getIndexType());
851   return parser.parseRegion(*body, ivsInfo, argTypes);
852 }
853 
854 void PolyForOp::print(OpAsmPrinter &p) { p.printGenericOp(*this); }
855 
856 void PolyForOp::getAsmBlockArgumentNames(Region &region,
857                                          OpAsmSetValueNameFn setNameFn) {
858   auto arrayAttr = getOperation()->getAttrOfType<ArrayAttr>("arg_names");
859   if (!arrayAttr)
860     return;
861   auto args = getRegion().front().getArguments();
862   auto e = std::min(arrayAttr.size(), args.size());
863   for (unsigned i = 0; i < e; ++i) {
864     if (auto strAttr = arrayAttr[i].dyn_cast<StringAttr>())
865       setNameFn(args[i], strAttr.getValue());
866   }
867 }
868 
869 //===----------------------------------------------------------------------===//
870 // Test removing op with inner ops.
871 //===----------------------------------------------------------------------===//
872 
873 namespace {
874 struct TestRemoveOpWithInnerOps
875     : public OpRewritePattern<TestOpWithRegionPattern> {
876   using OpRewritePattern<TestOpWithRegionPattern>::OpRewritePattern;
877 
878   void initialize() { setDebugName("TestRemoveOpWithInnerOps"); }
879 
880   LogicalResult matchAndRewrite(TestOpWithRegionPattern op,
881                                 PatternRewriter &rewriter) const override {
882     rewriter.eraseOp(op);
883     return success();
884   }
885 };
886 } // namespace
887 
888 void TestOpWithRegionPattern::getCanonicalizationPatterns(
889     RewritePatternSet &results, MLIRContext *context) {
890   results.add<TestRemoveOpWithInnerOps>(context);
891 }
892 
893 OpFoldResult TestOpWithRegionFold::fold(ArrayRef<Attribute> operands) {
894   return getOperand();
895 }
896 
897 OpFoldResult TestOpConstant::fold(ArrayRef<Attribute> operands) {
898   return getValue();
899 }
900 
901 LogicalResult TestOpWithVariadicResultsAndFolder::fold(
902     ArrayRef<Attribute> operands, SmallVectorImpl<OpFoldResult> &results) {
903   for (Value input : this->getOperands()) {
904     results.push_back(input);
905   }
906   return success();
907 }
908 
909 OpFoldResult TestOpInPlaceFold::fold(ArrayRef<Attribute> operands) {
910   assert(operands.size() == 1);
911   if (operands.front()) {
912     (*this)->setAttr("attr", operands.front());
913     return getResult();
914   }
915   return {};
916 }
917 
918 OpFoldResult TestPassthroughFold::fold(ArrayRef<Attribute> operands) {
919   return getOperand();
920 }
921 
922 LogicalResult OpWithInferTypeInterfaceOp::inferReturnTypes(
923     MLIRContext *, Optional<Location> location, ValueRange operands,
924     DictionaryAttr attributes, RegionRange regions,
925     SmallVectorImpl<Type> &inferredReturnTypes) {
926   if (operands[0].getType() != operands[1].getType()) {
927     return emitOptionalError(location, "operand type mismatch ",
928                              operands[0].getType(), " vs ",
929                              operands[1].getType());
930   }
931   inferredReturnTypes.assign({operands[0].getType()});
932   return success();
933 }
934 
935 LogicalResult OpWithShapedTypeInferTypeInterfaceOp::inferReturnTypeComponents(
936     MLIRContext *context, Optional<Location> location, ValueShapeRange operands,
937     DictionaryAttr attributes, RegionRange regions,
938     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
939   // Create return type consisting of the last element of the first operand.
940   auto operandType = operands.front().getType();
941   auto sval = operandType.dyn_cast<ShapedType>();
942   if (!sval) {
943     return emitOptionalError(location, "only shaped type operands allowed");
944   }
945   int64_t dim =
946       sval.hasRank() ? sval.getShape().front() : ShapedType::kDynamicSize;
947   auto type = IntegerType::get(context, 17);
948   inferredReturnShapes.push_back(ShapedTypeComponents({dim}, type));
949   return success();
950 }
951 
952 LogicalResult OpWithShapedTypeInferTypeInterfaceOp::reifyReturnTypeShapes(
953     OpBuilder &builder, ValueRange operands,
954     llvm::SmallVectorImpl<Value> &shapes) {
955   shapes = SmallVector<Value, 1>{
956       builder.createOrFold<tensor::DimOp>(getLoc(), operands.front(), 0)};
957   return success();
958 }
959 
960 LogicalResult OpWithResultShapeInterfaceOp::reifyReturnTypeShapes(
961     OpBuilder &builder, ValueRange operands,
962     llvm::SmallVectorImpl<Value> &shapes) {
963   Location loc = getLoc();
964   shapes.reserve(operands.size());
965   for (Value operand : llvm::reverse(operands)) {
966     auto rank = operand.getType().cast<RankedTensorType>().getRank();
967     auto currShape = llvm::to_vector<4>(
968         llvm::map_range(llvm::seq<int64_t>(0, rank), [&](int64_t dim) -> Value {
969           return builder.createOrFold<tensor::DimOp>(loc, operand, dim);
970         }));
971     shapes.push_back(builder.create<tensor::FromElementsOp>(
972         getLoc(), RankedTensorType::get({rank}, builder.getIndexType()),
973         currShape));
974   }
975   return success();
976 }
977 
978 LogicalResult OpWithResultShapePerDimInterfaceOp::reifyResultShapes(
979     OpBuilder &builder, ReifiedRankedShapedTypeDims &shapes) {
980   Location loc = getLoc();
981   shapes.reserve(getNumOperands());
982   for (Value operand : llvm::reverse(getOperands())) {
983     auto currShape = llvm::to_vector<4>(llvm::map_range(
984         llvm::seq<int64_t>(
985             0, operand.getType().cast<RankedTensorType>().getRank()),
986         [&](int64_t dim) -> Value {
987           return builder.createOrFold<tensor::DimOp>(loc, operand, dim);
988         }));
989     shapes.emplace_back(std::move(currShape));
990   }
991   return success();
992 }
993 
994 //===----------------------------------------------------------------------===//
995 // Test SideEffect interfaces
996 //===----------------------------------------------------------------------===//
997 
998 namespace {
999 /// A test resource for side effects.
1000 struct TestResource : public SideEffects::Resource::Base<TestResource> {
1001   StringRef getName() final { return "<Test>"; }
1002 };
1003 } // namespace
1004 
1005 static void testSideEffectOpGetEffect(
1006     Operation *op,
1007     SmallVectorImpl<SideEffects::EffectInstance<TestEffects::Effect>>
1008         &effects) {
1009   auto effectsAttr = op->getAttrOfType<AffineMapAttr>("effect_parameter");
1010   if (!effectsAttr)
1011     return;
1012 
1013   effects.emplace_back(TestEffects::Concrete::get(), effectsAttr);
1014 }
1015 
1016 void SideEffectOp::getEffects(
1017     SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
1018   // Check for an effects attribute on the op instance.
1019   ArrayAttr effectsAttr = (*this)->getAttrOfType<ArrayAttr>("effects");
1020   if (!effectsAttr)
1021     return;
1022 
1023   // If there is one, it is an array of dictionary attributes that hold
1024   // information on the effects of this operation.
1025   for (Attribute element : effectsAttr) {
1026     DictionaryAttr effectElement = element.cast<DictionaryAttr>();
1027 
1028     // Get the specific memory effect.
1029     MemoryEffects::Effect *effect =
1030         StringSwitch<MemoryEffects::Effect *>(
1031             effectElement.get("effect").cast<StringAttr>().getValue())
1032             .Case("allocate", MemoryEffects::Allocate::get())
1033             .Case("free", MemoryEffects::Free::get())
1034             .Case("read", MemoryEffects::Read::get())
1035             .Case("write", MemoryEffects::Write::get());
1036 
1037     // Check for a non-default resource to use.
1038     SideEffects::Resource *resource = SideEffects::DefaultResource::get();
1039     if (effectElement.get("test_resource"))
1040       resource = TestResource::get();
1041 
1042     // Check for a result to affect.
1043     if (effectElement.get("on_result"))
1044       effects.emplace_back(effect, getResult(), resource);
1045     else if (Attribute ref = effectElement.get("on_reference"))
1046       effects.emplace_back(effect, ref.cast<SymbolRefAttr>(), resource);
1047     else
1048       effects.emplace_back(effect, resource);
1049   }
1050 }
1051 
1052 void SideEffectOp::getEffects(
1053     SmallVectorImpl<TestEffects::EffectInstance> &effects) {
1054   testSideEffectOpGetEffect(getOperation(), effects);
1055 }
1056 
1057 //===----------------------------------------------------------------------===//
1058 // StringAttrPrettyNameOp
1059 //===----------------------------------------------------------------------===//
1060 
1061 // This op has fancy handling of its SSA result name.
1062 ParseResult StringAttrPrettyNameOp::parse(OpAsmParser &parser,
1063                                           OperationState &result) {
1064   // Add the result types.
1065   for (size_t i = 0, e = parser.getNumResults(); i != e; ++i)
1066     result.addTypes(parser.getBuilder().getIntegerType(32));
1067 
1068   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
1069     return failure();
1070 
1071   // If the attribute dictionary contains no 'names' attribute, infer it from
1072   // the SSA name (if specified).
1073   bool hadNames = llvm::any_of(result.attributes, [](NamedAttribute attr) {
1074     return attr.getName() == "names";
1075   });
1076 
1077   // If there was no name specified, check to see if there was a useful name
1078   // specified in the asm file.
1079   if (hadNames || parser.getNumResults() == 0)
1080     return success();
1081 
1082   SmallVector<StringRef, 4> names;
1083   auto *context = result.getContext();
1084 
1085   for (size_t i = 0, e = parser.getNumResults(); i != e; ++i) {
1086     auto resultName = parser.getResultName(i);
1087     StringRef nameStr;
1088     if (!resultName.first.empty() && !isdigit(resultName.first[0]))
1089       nameStr = resultName.first;
1090 
1091     names.push_back(nameStr);
1092   }
1093 
1094   auto namesAttr = parser.getBuilder().getStrArrayAttr(names);
1095   result.attributes.push_back({StringAttr::get(context, "names"), namesAttr});
1096   return success();
1097 }
1098 
1099 void StringAttrPrettyNameOp::print(OpAsmPrinter &p) {
1100   // Note that we only need to print the "name" attribute if the asmprinter
1101   // result name disagrees with it.  This can happen in strange cases, e.g.
1102   // when there are conflicts.
1103   bool namesDisagree = getNames().size() != getNumResults();
1104 
1105   SmallString<32> resultNameStr;
1106   for (size_t i = 0, e = getNumResults(); i != e && !namesDisagree; ++i) {
1107     resultNameStr.clear();
1108     llvm::raw_svector_ostream tmpStream(resultNameStr);
1109     p.printOperand(getResult(i), tmpStream);
1110 
1111     auto expectedName = getNames()[i].dyn_cast<StringAttr>();
1112     if (!expectedName ||
1113         tmpStream.str().drop_front() != expectedName.getValue()) {
1114       namesDisagree = true;
1115     }
1116   }
1117 
1118   if (namesDisagree)
1119     p.printOptionalAttrDictWithKeyword((*this)->getAttrs());
1120   else
1121     p.printOptionalAttrDictWithKeyword((*this)->getAttrs(), {"names"});
1122 }
1123 
1124 // We set the SSA name in the asm syntax to the contents of the name
1125 // attribute.
1126 void StringAttrPrettyNameOp::getAsmResultNames(
1127     function_ref<void(Value, StringRef)> setNameFn) {
1128 
1129   auto value = getNames();
1130   for (size_t i = 0, e = value.size(); i != e; ++i)
1131     if (auto str = value[i].dyn_cast<StringAttr>())
1132       if (!str.getValue().empty())
1133         setNameFn(getResult(i), str.getValue());
1134 }
1135 
1136 //===----------------------------------------------------------------------===//
1137 // ResultTypeWithTraitOp
1138 //===----------------------------------------------------------------------===//
1139 
1140 LogicalResult ResultTypeWithTraitOp::verify() {
1141   if ((*this)->getResultTypes()[0].hasTrait<TypeTrait::TestTypeTrait>())
1142     return success();
1143   return emitError("result type should have trait 'TestTypeTrait'");
1144 }
1145 
1146 //===----------------------------------------------------------------------===//
1147 // AttrWithTraitOp
1148 //===----------------------------------------------------------------------===//
1149 
1150 LogicalResult AttrWithTraitOp::verify() {
1151   if (getAttr().hasTrait<AttributeTrait::TestAttrTrait>())
1152     return success();
1153   return emitError("'attr' attribute should have trait 'TestAttrTrait'");
1154 }
1155 
1156 //===----------------------------------------------------------------------===//
1157 // RegionIfOp
1158 //===----------------------------------------------------------------------===//
1159 
1160 void RegionIfOp::print(OpAsmPrinter &p) {
1161   p << " ";
1162   p.printOperands(getOperands());
1163   p << ": " << getOperandTypes();
1164   p.printArrowTypeList(getResultTypes());
1165   p << " then ";
1166   p.printRegion(getThenRegion(),
1167                 /*printEntryBlockArgs=*/true,
1168                 /*printBlockTerminators=*/true);
1169   p << " else ";
1170   p.printRegion(getElseRegion(),
1171                 /*printEntryBlockArgs=*/true,
1172                 /*printBlockTerminators=*/true);
1173   p << " join ";
1174   p.printRegion(getJoinRegion(),
1175                 /*printEntryBlockArgs=*/true,
1176                 /*printBlockTerminators=*/true);
1177 }
1178 
1179 ParseResult RegionIfOp::parse(OpAsmParser &parser, OperationState &result) {
1180   SmallVector<OpAsmParser::OperandType, 2> operandInfos;
1181   SmallVector<Type, 2> operandTypes;
1182 
1183   result.regions.reserve(3);
1184   Region *thenRegion = result.addRegion();
1185   Region *elseRegion = result.addRegion();
1186   Region *joinRegion = result.addRegion();
1187 
1188   // Parse operand, type and arrow type lists.
1189   if (parser.parseOperandList(operandInfos) ||
1190       parser.parseColonTypeList(operandTypes) ||
1191       parser.parseArrowTypeList(result.types))
1192     return failure();
1193 
1194   // Parse all attached regions.
1195   if (parser.parseKeyword("then") || parser.parseRegion(*thenRegion, {}, {}) ||
1196       parser.parseKeyword("else") || parser.parseRegion(*elseRegion, {}, {}) ||
1197       parser.parseKeyword("join") || parser.parseRegion(*joinRegion, {}, {}))
1198     return failure();
1199 
1200   return parser.resolveOperands(operandInfos, operandTypes,
1201                                 parser.getCurrentLocation(), result.operands);
1202 }
1203 
1204 OperandRange RegionIfOp::getSuccessorEntryOperands(unsigned index) {
1205   assert(index < 2 && "invalid region index");
1206   return getOperands();
1207 }
1208 
1209 void RegionIfOp::getSuccessorRegions(
1210     Optional<unsigned> index, ArrayRef<Attribute> operands,
1211     SmallVectorImpl<RegionSuccessor> &regions) {
1212   // We always branch to the join region.
1213   if (index.hasValue()) {
1214     if (index.getValue() < 2)
1215       regions.push_back(RegionSuccessor(&getJoinRegion(), getJoinArgs()));
1216     else
1217       regions.push_back(RegionSuccessor(getResults()));
1218     return;
1219   }
1220 
1221   // The then and else regions are the entry regions of this op.
1222   regions.push_back(RegionSuccessor(&getThenRegion(), getThenArgs()));
1223   regions.push_back(RegionSuccessor(&getElseRegion(), getElseArgs()));
1224 }
1225 
1226 void RegionIfOp::getRegionInvocationBounds(
1227     ArrayRef<Attribute> operands,
1228     SmallVectorImpl<InvocationBounds> &invocationBounds) {
1229   // Each region is invoked at most once.
1230   invocationBounds.assign(/*NumElts=*/3, /*Elt=*/{0, 1});
1231 }
1232 
1233 //===----------------------------------------------------------------------===//
1234 // AnyCondOp
1235 //===----------------------------------------------------------------------===//
1236 
1237 void AnyCondOp::getSuccessorRegions(Optional<unsigned> index,
1238                                     ArrayRef<Attribute> operands,
1239                                     SmallVectorImpl<RegionSuccessor> &regions) {
1240   // The parent op branches into the only region, and the region branches back
1241   // to the parent op.
1242   if (index)
1243     regions.emplace_back(&getRegion());
1244   else
1245     regions.emplace_back(getResults());
1246 }
1247 
1248 void AnyCondOp::getRegionInvocationBounds(
1249     ArrayRef<Attribute> operands,
1250     SmallVectorImpl<InvocationBounds> &invocationBounds) {
1251   invocationBounds.emplace_back(1, 1);
1252 }
1253 
1254 //===----------------------------------------------------------------------===//
1255 // SingleNoTerminatorCustomAsmOp
1256 //===----------------------------------------------------------------------===//
1257 
1258 ParseResult SingleNoTerminatorCustomAsmOp::parse(OpAsmParser &parser,
1259                                                  OperationState &state) {
1260   Region *body = state.addRegion();
1261   if (parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{}))
1262     return failure();
1263   return success();
1264 }
1265 
1266 void SingleNoTerminatorCustomAsmOp::print(OpAsmPrinter &printer) {
1267   printer.printRegion(
1268       getRegion(), /*printEntryBlockArgs=*/false,
1269       // This op has a single block without terminators. But explicitly mark
1270       // as not printing block terminators for testing.
1271       /*printBlockTerminators=*/false);
1272 }
1273 
1274 #include "TestOpEnums.cpp.inc"
1275 #include "TestOpInterfaces.cpp.inc"
1276 #include "TestOpStructs.cpp.inc"
1277 #include "TestTypeInterfaces.cpp.inc"
1278 
1279 #define GET_OP_CLASSES
1280 #include "TestOps.cpp.inc"
1281