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 Format* operations
272 //===----------------------------------------------------------------------===//
273 
274 //===----------------------------------------------------------------------===//
275 // Parsing
276 
277 static ParseResult parseCustomDirectiveOperands(
278     OpAsmParser &parser, OpAsmParser::OperandType &operand,
279     Optional<OpAsmParser::OperandType> &optOperand,
280     SmallVectorImpl<OpAsmParser::OperandType> &varOperands) {
281   if (parser.parseOperand(operand))
282     return failure();
283   if (succeeded(parser.parseOptionalComma())) {
284     optOperand.emplace();
285     if (parser.parseOperand(*optOperand))
286       return failure();
287   }
288   if (parser.parseArrow() || parser.parseLParen() ||
289       parser.parseOperandList(varOperands) || parser.parseRParen())
290     return failure();
291   return success();
292 }
293 static ParseResult
294 parseCustomDirectiveResults(OpAsmParser &parser, Type &operandType,
295                             Type &optOperandType,
296                             SmallVectorImpl<Type> &varOperandTypes) {
297   if (parser.parseColon())
298     return failure();
299 
300   if (parser.parseType(operandType))
301     return failure();
302   if (succeeded(parser.parseOptionalComma())) {
303     if (parser.parseType(optOperandType))
304       return failure();
305   }
306   if (parser.parseArrow() || parser.parseLParen() ||
307       parser.parseTypeList(varOperandTypes) || parser.parseRParen())
308     return failure();
309   return success();
310 }
311 static ParseResult parseCustomDirectiveOperandsAndTypes(
312     OpAsmParser &parser, OpAsmParser::OperandType &operand,
313     Optional<OpAsmParser::OperandType> &optOperand,
314     SmallVectorImpl<OpAsmParser::OperandType> &varOperands, Type &operandType,
315     Type &optOperandType, SmallVectorImpl<Type> &varOperandTypes) {
316   if (parseCustomDirectiveOperands(parser, operand, optOperand, varOperands) ||
317       parseCustomDirectiveResults(parser, operandType, optOperandType,
318                                   varOperandTypes))
319     return failure();
320   return success();
321 }
322 static ParseResult parseCustomDirectiveRegions(
323     OpAsmParser &parser, Region &region,
324     SmallVectorImpl<std::unique_ptr<Region>> &varRegions) {
325   if (parser.parseRegion(region))
326     return failure();
327   if (failed(parser.parseOptionalComma()))
328     return success();
329   std::unique_ptr<Region> varRegion = std::make_unique<Region>();
330   if (parser.parseRegion(*varRegion))
331     return failure();
332   varRegions.emplace_back(std::move(varRegion));
333   return success();
334 }
335 static ParseResult
336 parseCustomDirectiveSuccessors(OpAsmParser &parser, Block *&successor,
337                                SmallVectorImpl<Block *> &varSuccessors) {
338   if (parser.parseSuccessor(successor))
339     return failure();
340   if (failed(parser.parseOptionalComma()))
341     return success();
342   Block *varSuccessor;
343   if (parser.parseSuccessor(varSuccessor))
344     return failure();
345   varSuccessors.append(2, varSuccessor);
346   return success();
347 }
348 
349 //===----------------------------------------------------------------------===//
350 // Printing
351 
352 static void printCustomDirectiveOperands(OpAsmPrinter &printer, Value operand,
353                                          Value optOperand,
354                                          OperandRange varOperands) {
355   printer << operand;
356   if (optOperand)
357     printer << ", " << optOperand;
358   printer << " -> (" << varOperands << ")";
359 }
360 static void printCustomDirectiveResults(OpAsmPrinter &printer, Type operandType,
361                                         Type optOperandType,
362                                         TypeRange varOperandTypes) {
363   printer << " : " << operandType;
364   if (optOperandType)
365     printer << ", " << optOperandType;
366   printer << " -> (" << varOperandTypes << ")";
367 }
368 static void
369 printCustomDirectiveOperandsAndTypes(OpAsmPrinter &printer, Value operand,
370                                      Value optOperand, OperandRange varOperands,
371                                      Type operandType, Type optOperandType,
372                                      TypeRange varOperandTypes) {
373   printCustomDirectiveOperands(printer, operand, optOperand, varOperands);
374   printCustomDirectiveResults(printer, operandType, optOperandType,
375                               varOperandTypes);
376 }
377 static void printCustomDirectiveRegions(OpAsmPrinter &printer, Region &region,
378                                         MutableArrayRef<Region> varRegions) {
379   printer.printRegion(region);
380   if (!varRegions.empty()) {
381     printer << ", ";
382     for (Region &region : varRegions)
383       printer.printRegion(region);
384   }
385 }
386 static void printCustomDirectiveSuccessors(OpAsmPrinter &printer,
387                                            Block *successor,
388                                            SuccessorRange varSuccessors) {
389   printer << successor;
390   if (!varSuccessors.empty())
391     printer << ", " << varSuccessors.front();
392 }
393 
394 //===----------------------------------------------------------------------===//
395 // Test IsolatedRegionOp - parse passthrough region arguments.
396 //===----------------------------------------------------------------------===//
397 
398 static ParseResult parseIsolatedRegionOp(OpAsmParser &parser,
399                                          OperationState &result) {
400   OpAsmParser::OperandType argInfo;
401   Type argType = parser.getBuilder().getIndexType();
402 
403   // Parse the input operand.
404   if (parser.parseOperand(argInfo) ||
405       parser.resolveOperand(argInfo, argType, result.operands))
406     return failure();
407 
408   // Parse the body region, and reuse the operand info as the argument info.
409   Region *body = result.addRegion();
410   return parser.parseRegion(*body, argInfo, argType,
411                             /*enableNameShadowing=*/true);
412 }
413 
414 static void print(OpAsmPrinter &p, IsolatedRegionOp op) {
415   p << "test.isolated_region ";
416   p.printOperand(op.getOperand());
417   p.shadowRegionArgs(op.region(), op.getOperand());
418   p.printRegion(op.region(), /*printEntryBlockArgs=*/false);
419 }
420 
421 //===----------------------------------------------------------------------===//
422 // Test SSACFGRegionOp
423 //===----------------------------------------------------------------------===//
424 
425 RegionKind SSACFGRegionOp::getRegionKind(unsigned index) {
426   return RegionKind::SSACFG;
427 }
428 
429 //===----------------------------------------------------------------------===//
430 // Test GraphRegionOp
431 //===----------------------------------------------------------------------===//
432 
433 static ParseResult parseGraphRegionOp(OpAsmParser &parser,
434                                       OperationState &result) {
435   // Parse the body region, and reuse the operand info as the argument info.
436   Region *body = result.addRegion();
437   return parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{});
438 }
439 
440 static void print(OpAsmPrinter &p, GraphRegionOp op) {
441   p << "test.graph_region ";
442   p.printRegion(op.region(), /*printEntryBlockArgs=*/false);
443 }
444 
445 RegionKind GraphRegionOp::getRegionKind(unsigned index) {
446   return RegionKind::Graph;
447 }
448 
449 //===----------------------------------------------------------------------===//
450 // Test AffineScopeOp
451 //===----------------------------------------------------------------------===//
452 
453 static ParseResult parseAffineScopeOp(OpAsmParser &parser,
454                                       OperationState &result) {
455   // Parse the body region, and reuse the operand info as the argument info.
456   Region *body = result.addRegion();
457   return parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{});
458 }
459 
460 static void print(OpAsmPrinter &p, AffineScopeOp op) {
461   p << "test.affine_scope ";
462   p.printRegion(op.region(), /*printEntryBlockArgs=*/false);
463 }
464 
465 //===----------------------------------------------------------------------===//
466 // Test parser.
467 //===----------------------------------------------------------------------===//
468 
469 static ParseResult parseWrappedKeywordOp(OpAsmParser &parser,
470                                          OperationState &result) {
471   StringRef keyword;
472   if (parser.parseKeyword(&keyword))
473     return failure();
474   result.addAttribute("keyword", parser.getBuilder().getStringAttr(keyword));
475   return success();
476 }
477 
478 static void print(OpAsmPrinter &p, WrappedKeywordOp op) {
479   p << WrappedKeywordOp::getOperationName() << " " << op.keyword();
480 }
481 
482 //===----------------------------------------------------------------------===//
483 // Test WrapRegionOp - wrapping op exercising `parseGenericOperation()`.
484 
485 static ParseResult parseWrappingRegionOp(OpAsmParser &parser,
486                                          OperationState &result) {
487   if (parser.parseKeyword("wraps"))
488     return failure();
489 
490   // Parse the wrapped op in a region
491   Region &body = *result.addRegion();
492   body.push_back(new Block);
493   Block &block = body.back();
494   Operation *wrapped_op = parser.parseGenericOperation(&block, block.begin());
495   if (!wrapped_op)
496     return failure();
497 
498   // Create a return terminator in the inner region, pass as operand to the
499   // terminator the returned values from the wrapped operation.
500   SmallVector<Value, 8> return_operands(wrapped_op->getResults());
501   OpBuilder builder(parser.getBuilder().getContext());
502   builder.setInsertionPointToEnd(&block);
503   builder.create<TestReturnOp>(wrapped_op->getLoc(), return_operands);
504 
505   // Get the results type for the wrapping op from the terminator operands.
506   Operation &return_op = body.back().back();
507   result.types.append(return_op.operand_type_begin(),
508                       return_op.operand_type_end());
509 
510   // Use the location of the wrapped op for the "test.wrapping_region" op.
511   result.location = wrapped_op->getLoc();
512 
513   return success();
514 }
515 
516 static void print(OpAsmPrinter &p, WrappingRegionOp op) {
517   p << op.getOperationName() << " wraps ";
518   p.printGenericOp(&op.region().front().front());
519 }
520 
521 //===----------------------------------------------------------------------===//
522 // Test PolyForOp - parse list of region arguments.
523 //===----------------------------------------------------------------------===//
524 
525 static ParseResult parsePolyForOp(OpAsmParser &parser, OperationState &result) {
526   SmallVector<OpAsmParser::OperandType, 4> ivsInfo;
527   // Parse list of region arguments without a delimiter.
528   if (parser.parseRegionArgumentList(ivsInfo))
529     return failure();
530 
531   // Parse the body region.
532   Region *body = result.addRegion();
533   auto &builder = parser.getBuilder();
534   SmallVector<Type, 4> argTypes(ivsInfo.size(), builder.getIndexType());
535   return parser.parseRegion(*body, ivsInfo, argTypes);
536 }
537 
538 //===----------------------------------------------------------------------===//
539 // Test removing op with inner ops.
540 //===----------------------------------------------------------------------===//
541 
542 namespace {
543 struct TestRemoveOpWithInnerOps
544     : public OpRewritePattern<TestOpWithRegionPattern> {
545   using OpRewritePattern<TestOpWithRegionPattern>::OpRewritePattern;
546 
547   LogicalResult matchAndRewrite(TestOpWithRegionPattern op,
548                                 PatternRewriter &rewriter) const override {
549     rewriter.eraseOp(op);
550     return success();
551   }
552 };
553 } // end anonymous namespace
554 
555 void TestOpWithRegionPattern::getCanonicalizationPatterns(
556     OwningRewritePatternList &results, MLIRContext *context) {
557   results.insert<TestRemoveOpWithInnerOps>(context);
558 }
559 
560 OpFoldResult TestOpWithRegionFold::fold(ArrayRef<Attribute> operands) {
561   return operand();
562 }
563 
564 LogicalResult TestOpWithVariadicResultsAndFolder::fold(
565     ArrayRef<Attribute> operands, SmallVectorImpl<OpFoldResult> &results) {
566   for (Value input : this->operands()) {
567     results.push_back(input);
568   }
569   return success();
570 }
571 
572 OpFoldResult TestOpInPlaceFold::fold(ArrayRef<Attribute> operands) {
573   assert(operands.size() == 1);
574   if (operands.front()) {
575     setAttr("attr", operands.front());
576     return getResult();
577   }
578   return {};
579 }
580 
581 LogicalResult OpWithInferTypeInterfaceOp::inferReturnTypes(
582     MLIRContext *, Optional<Location> location, ValueRange operands,
583     DictionaryAttr attributes, RegionRange regions,
584     SmallVectorImpl<Type> &inferredReturnTypes) {
585   if (operands[0].getType() != operands[1].getType()) {
586     return emitOptionalError(location, "operand type mismatch ",
587                              operands[0].getType(), " vs ",
588                              operands[1].getType());
589   }
590   inferredReturnTypes.assign({operands[0].getType()});
591   return success();
592 }
593 
594 LogicalResult OpWithShapedTypeInferTypeInterfaceOp::inferReturnTypeComponents(
595     MLIRContext *context, Optional<Location> location, ValueRange operands,
596     DictionaryAttr attributes, RegionRange regions,
597     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
598   // Create return type consisting of the last element of the first operand.
599   auto operandType = *operands.getTypes().begin();
600   auto sval = operandType.dyn_cast<ShapedType>();
601   if (!sval) {
602     return emitOptionalError(location, "only shaped type operands allowed");
603   }
604   int64_t dim =
605       sval.hasRank() ? sval.getShape().front() : ShapedType::kDynamicSize;
606   auto type = IntegerType::get(17, context);
607   inferredReturnShapes.push_back(ShapedTypeComponents({dim}, type));
608   return success();
609 }
610 
611 LogicalResult OpWithShapedTypeInferTypeInterfaceOp::reifyReturnTypeShapes(
612     OpBuilder &builder, llvm::SmallVectorImpl<Value> &shapes) {
613   shapes = SmallVector<Value, 1>{
614       builder.createOrFold<DimOp>(getLoc(), getOperand(0), 0)};
615   return success();
616 }
617 
618 //===----------------------------------------------------------------------===//
619 // Test SideEffect interfaces
620 //===----------------------------------------------------------------------===//
621 
622 namespace {
623 /// A test resource for side effects.
624 struct TestResource : public SideEffects::Resource::Base<TestResource> {
625   StringRef getName() final { return "<Test>"; }
626 };
627 } // end anonymous namespace
628 
629 void SideEffectOp::getEffects(
630     SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
631   // Check for an effects attribute on the op instance.
632   ArrayAttr effectsAttr = getAttrOfType<ArrayAttr>("effects");
633   if (!effectsAttr)
634     return;
635 
636   // If there is one, it is an array of dictionary attributes that hold
637   // information on the effects of this operation.
638   for (Attribute element : effectsAttr) {
639     DictionaryAttr effectElement = element.cast<DictionaryAttr>();
640 
641     // Get the specific memory effect.
642     MemoryEffects::Effect *effect =
643         llvm::StringSwitch<MemoryEffects::Effect *>(
644             effectElement.get("effect").cast<StringAttr>().getValue())
645             .Case("allocate", MemoryEffects::Allocate::get())
646             .Case("free", MemoryEffects::Free::get())
647             .Case("read", MemoryEffects::Read::get())
648             .Case("write", MemoryEffects::Write::get());
649 
650     // Check for a result to affect.
651     Value value;
652     if (effectElement.get("on_result"))
653       value = getResult();
654 
655     // Check for a non-default resource to use.
656     SideEffects::Resource *resource = SideEffects::DefaultResource::get();
657     if (effectElement.get("test_resource"))
658       resource = TestResource::get();
659 
660     effects.emplace_back(effect, value, resource);
661   }
662 }
663 
664 //===----------------------------------------------------------------------===//
665 // StringAttrPrettyNameOp
666 //===----------------------------------------------------------------------===//
667 
668 // This op has fancy handling of its SSA result name.
669 static ParseResult parseStringAttrPrettyNameOp(OpAsmParser &parser,
670                                                OperationState &result) {
671   // Add the result types.
672   for (size_t i = 0, e = parser.getNumResults(); i != e; ++i)
673     result.addTypes(parser.getBuilder().getIntegerType(32));
674 
675   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
676     return failure();
677 
678   // If the attribute dictionary contains no 'names' attribute, infer it from
679   // the SSA name (if specified).
680   bool hadNames = llvm::any_of(result.attributes, [](NamedAttribute attr) {
681     return attr.first == "names";
682   });
683 
684   // If there was no name specified, check to see if there was a useful name
685   // specified in the asm file.
686   if (hadNames || parser.getNumResults() == 0)
687     return success();
688 
689   SmallVector<StringRef, 4> names;
690   auto *context = result.getContext();
691 
692   for (size_t i = 0, e = parser.getNumResults(); i != e; ++i) {
693     auto resultName = parser.getResultName(i);
694     StringRef nameStr;
695     if (!resultName.first.empty() && !isdigit(resultName.first[0]))
696       nameStr = resultName.first;
697 
698     names.push_back(nameStr);
699   }
700 
701   auto namesAttr = parser.getBuilder().getStrArrayAttr(names);
702   result.attributes.push_back({Identifier::get("names", context), namesAttr});
703   return success();
704 }
705 
706 static void print(OpAsmPrinter &p, StringAttrPrettyNameOp op) {
707   p << "test.string_attr_pretty_name";
708 
709   // Note that we only need to print the "name" attribute if the asmprinter
710   // result name disagrees with it.  This can happen in strange cases, e.g.
711   // when there are conflicts.
712   bool namesDisagree = op.names().size() != op.getNumResults();
713 
714   SmallString<32> resultNameStr;
715   for (size_t i = 0, e = op.getNumResults(); i != e && !namesDisagree; ++i) {
716     resultNameStr.clear();
717     llvm::raw_svector_ostream tmpStream(resultNameStr);
718     p.printOperand(op.getResult(i), tmpStream);
719 
720     auto expectedName = op.names()[i].dyn_cast<StringAttr>();
721     if (!expectedName ||
722         tmpStream.str().drop_front() != expectedName.getValue()) {
723       namesDisagree = true;
724     }
725   }
726 
727   if (namesDisagree)
728     p.printOptionalAttrDictWithKeyword(op.getAttrs());
729   else
730     p.printOptionalAttrDictWithKeyword(op.getAttrs(), {"names"});
731 }
732 
733 // We set the SSA name in the asm syntax to the contents of the name
734 // attribute.
735 void StringAttrPrettyNameOp::getAsmResultNames(
736     function_ref<void(Value, StringRef)> setNameFn) {
737 
738   auto value = names();
739   for (size_t i = 0, e = value.size(); i != e; ++i)
740     if (auto str = value[i].dyn_cast<StringAttr>())
741       if (!str.getValue().empty())
742         setNameFn(getResult(i), str.getValue());
743 }
744 
745 //===----------------------------------------------------------------------===//
746 // RegionIfOp
747 //===----------------------------------------------------------------------===//
748 
749 static void print(OpAsmPrinter &p, RegionIfOp op) {
750   p << RegionIfOp::getOperationName() << " ";
751   p.printOperands(op.getOperands());
752   p << ": " << op.getOperandTypes();
753   p.printArrowTypeList(op.getResultTypes());
754   p << " then";
755   p.printRegion(op.thenRegion(),
756                 /*printEntryBlockArgs=*/true,
757                 /*printBlockTerminators=*/true);
758   p << " else";
759   p.printRegion(op.elseRegion(),
760                 /*printEntryBlockArgs=*/true,
761                 /*printBlockTerminators=*/true);
762   p << " join";
763   p.printRegion(op.joinRegion(),
764                 /*printEntryBlockArgs=*/true,
765                 /*printBlockTerminators=*/true);
766 }
767 
768 static ParseResult parseRegionIfOp(OpAsmParser &parser,
769                                    OperationState &result) {
770   SmallVector<OpAsmParser::OperandType, 2> operandInfos;
771   SmallVector<Type, 2> operandTypes;
772 
773   result.regions.reserve(3);
774   Region *thenRegion = result.addRegion();
775   Region *elseRegion = result.addRegion();
776   Region *joinRegion = result.addRegion();
777 
778   // Parse operand, type and arrow type lists.
779   if (parser.parseOperandList(operandInfos) ||
780       parser.parseColonTypeList(operandTypes) ||
781       parser.parseArrowTypeList(result.types))
782     return failure();
783 
784   // Parse all attached regions.
785   if (parser.parseKeyword("then") || parser.parseRegion(*thenRegion, {}, {}) ||
786       parser.parseKeyword("else") || parser.parseRegion(*elseRegion, {}, {}) ||
787       parser.parseKeyword("join") || parser.parseRegion(*joinRegion, {}, {}))
788     return failure();
789 
790   return parser.resolveOperands(operandInfos, operandTypes,
791                                 parser.getCurrentLocation(), result.operands);
792 }
793 
794 OperandRange RegionIfOp::getSuccessorEntryOperands(unsigned index) {
795   assert(index < 2 && "invalid region index");
796   return getOperands();
797 }
798 
799 void RegionIfOp::getSuccessorRegions(
800     Optional<unsigned> index, ArrayRef<Attribute> operands,
801     SmallVectorImpl<RegionSuccessor> &regions) {
802   // We always branch to the join region.
803   if (index.hasValue()) {
804     if (index.getValue() < 2)
805       regions.push_back(RegionSuccessor(&joinRegion(), getJoinArgs()));
806     else
807       regions.push_back(RegionSuccessor(getResults()));
808     return;
809   }
810 
811   // The then and else regions are the entry regions of this op.
812   regions.push_back(RegionSuccessor(&thenRegion(), getThenArgs()));
813   regions.push_back(RegionSuccessor(&elseRegion(), getElseArgs()));
814 }
815 
816 #include "TestOpEnums.cpp.inc"
817 #include "TestOpStructs.cpp.inc"
818 #include "TestTypeInterfaces.cpp.inc"
819 
820 #define GET_OP_CLASSES
821 #include "TestOps.cpp.inc"
822