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