1//===-- TestOps.td - Test dialect operation definitions ----*- tablegen -*-===//
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#ifndef TEST_OPS
10#define TEST_OPS
11
12include "mlir/Dialect/DLTI/DLTIBase.td"
13include "mlir/IR/OpBase.td"
14include "mlir/IR/OpAsmInterface.td"
15include "mlir/IR/RegionKindInterface.td"
16include "mlir/IR/SymbolInterfaces.td"
17include "mlir/Interfaces/CallInterfaces.td"
18include "mlir/Interfaces/ControlFlowInterfaces.td"
19include "mlir/Interfaces/CopyOpInterface.td"
20include "mlir/Interfaces/DataLayoutInterfaces.td"
21include "mlir/Interfaces/InferTypeOpInterface.td"
22include "mlir/Interfaces/SideEffectInterfaces.td"
23include "TestInterfaces.td"
24
25def Test_Dialect : Dialect {
26  let name = "test";
27  let cppNamespace = "::mlir::test";
28  let hasConstantMaterializer = 1;
29  let hasOperationAttrVerify = 1;
30  let hasRegionArgAttrVerify = 1;
31  let hasRegionResultAttrVerify = 1;
32  let hasOperationInterfaceFallback = 1;
33  let dependentDialects = ["::mlir::DLTIDialect"];
34
35  let extraClassDeclaration = [{
36    void registerAttributes();
37    void registerTypes();
38
39    Attribute parseAttribute(DialectAsmParser &parser,
40                             Type type) const override;
41    void printAttribute(Attribute attr,
42                        DialectAsmPrinter &printer) const override;
43
44    // Provides a custom printing/parsing for some operations.
45    Optional<ParseOpHook>
46      getParseOperationHook(StringRef opName) const override;
47    LogicalResult printOperation(Operation *op,
48                                 OpAsmPrinter &printer) const override;
49
50    ~TestDialect();
51  private:
52    // Storage for a custom fallback interface.
53    void *fallbackEffectOpInterfaces;
54
55  }];
56}
57
58class TEST_Op<string mnemonic, list<OpTrait> traits = []> :
59    Op<Test_Dialect, mnemonic, traits>;
60
61//===----------------------------------------------------------------------===//
62// Test Types
63//===----------------------------------------------------------------------===//
64
65def IntTypesOp : TEST_Op<"int_types"> {
66  let results = (outs
67    AnyI16:$any_i16,
68    SI32:$si32,
69    UI64:$ui64,
70    AnyInteger:$any_int
71  );
72}
73
74def ComplexF64 : Complex<F64>;
75def ComplexOp : TEST_Op<"complex_f64"> {
76  let results = (outs ComplexF64);
77}
78
79def ComplexTensorOp : TEST_Op<"complex_f64_tensor"> {
80  let results = (outs TensorOf<[ComplexF64]>);
81}
82
83def TupleOp : TEST_Op<"tuple_32_bit"> {
84  let results = (outs TupleOf<[I32, F32]>);
85}
86
87def NestedTupleOp : TEST_Op<"nested_tuple_32_bit"> {
88  let results = (outs NestedTupleOf<[I32, F32]>);
89}
90
91def TakesStaticMemRefOp : TEST_Op<"takes_static_memref"> {
92  let arguments = (ins AnyStaticShapeMemRef:$x);
93}
94
95def RankLessThan2I8F32MemRefOp : TEST_Op<"rank_less_than_2_I8_F32_memref"> {
96  let results = (outs MemRefRankOf<[I8, F32], [0, 1]>);
97}
98
99def NDTensorOfOp : TEST_Op<"nd_tensor_of"> {
100  let arguments = (ins
101    0DTensorOf<[F32]>:$arg0,
102    1DTensorOf<[F32]>:$arg1,
103    2DTensorOf<[I16]>:$arg2,
104    3DTensorOf<[I16]>:$arg3,
105    4DTensorOf<[I16]>:$arg4
106  );
107}
108
109def RankedTensorOp : TEST_Op<"ranked_tensor_op"> {
110  let arguments = (ins AnyRankedTensor:$input);
111}
112
113def MultiTensorRankOf : TEST_Op<"multi_tensor_rank_of"> {
114  let arguments = (ins
115    TensorRankOf<[I8, I32, F32], [0, 1]>:$arg0
116  );
117}
118
119def TEST_TestType : DialectType<Test_Dialect,
120    CPred<"$_self.isa<::mlir::test::TestType>()">, "test">,
121    BuildableType<"$_builder.getType<::mlir::test::TestType>()">;
122
123//===----------------------------------------------------------------------===//
124// Test Symbols
125//===----------------------------------------------------------------------===//
126
127def SymbolOp : TEST_Op<"symbol", [Symbol]> {
128  let summary =  "operation which defines a new symbol";
129  let arguments = (ins StrAttr:$sym_name,
130                       OptionalAttr<StrAttr>:$sym_visibility);
131}
132
133def SymbolScopeOp : TEST_Op<"symbol_scope",
134    [SymbolTable, SingleBlockImplicitTerminator<"TerminatorOp">]> {
135  let summary =  "operation which defines a new symbol table";
136  let regions = (region SizedRegion<1>:$region);
137}
138
139def SymbolTableRegionOp : TEST_Op<"symbol_table_region", [SymbolTable]> {
140  let summary =  "operation which defines a new symbol table without a "
141                 "restriction on a terminator";
142  let regions = (region SizedRegion<1>:$region);
143}
144
145//===----------------------------------------------------------------------===//
146// Test Operands
147//===----------------------------------------------------------------------===//
148
149def MixedNormalVariadicOperandOp : TEST_Op<
150    "mixed_normal_variadic_operand", [SameVariadicOperandSize]> {
151  let arguments = (ins
152    Variadic<AnyTensor>:$input1,
153    AnyTensor:$input2,
154    Variadic<AnyTensor>:$input3
155  );
156}
157def VariadicWithSameOperandsResult :
158      TEST_Op<"variadic_with_same_operand_results",
159              [SameOperandsAndResultType]> {
160  let arguments = (ins Variadic<AnySignlessInteger>:$operands);
161  let results = (outs AnySignlessInteger:$result);
162}
163
164def SameOperandsResultType : TEST_Op<
165    "same_operand_result_type", [SameOperandsAndResultType]> {
166  let arguments = (ins AnyTensor:$operand);
167  let results = (outs AnyTensor:$result);
168}
169
170//===----------------------------------------------------------------------===//
171// Test Results
172//===----------------------------------------------------------------------===//
173
174def MixedNormalVariadicResults : TEST_Op<
175    "mixed_normal_variadic_result", [SameVariadicResultSize]> {
176  let results = (outs
177    Variadic<AnyTensor>:$output1,
178    AnyTensor:$output2,
179    Variadic<AnyTensor>:$output3
180  );
181}
182
183//===----------------------------------------------------------------------===//
184// Test Attributes
185//===----------------------------------------------------------------------===//
186
187def NonNegIntAttrOp : TEST_Op<"non_negative_int_attr"> {
188  let arguments = (ins
189      Confined<I32Attr, [IntNonNegative]>:$i32attr,
190      Confined<I64Attr, [IntNonNegative]>:$i64attr
191  );
192}
193
194def PositiveIntAttrOp : TEST_Op<"positive_int_attr"> {
195  let arguments = (ins
196      Confined<I32Attr, [IntPositive]>:$i32attr,
197      Confined<I64Attr, [IntPositive]>:$i64attr
198  );
199}
200
201def TypeArrayAttrOp : TEST_Op<"type_array_attr"> {
202  let arguments = (ins TypeArrayAttr:$attr);
203}
204def TypeArrayAttrWithDefaultOp : TEST_Op<"type_array_attr_with_default"> {
205  let arguments = (ins DefaultValuedAttr<TypeArrayAttr, "{}">:$attr);
206}
207def TypeStringAttrWithTypeOp : TEST_Op<"string_attr_with_type"> {
208  let arguments = (ins TypedStrAttr<AnyType>:$attr);
209  let assemblyFormat = "$attr attr-dict";
210}
211
212def StrCaseA: StrEnumAttrCase<"A">;
213def StrCaseB: StrEnumAttrCase<"B">;
214
215def SomeStrEnum: StrEnumAttr<
216  "SomeStrEnum", "", [StrCaseA, StrCaseB]>;
217
218def StrEnumAttrOp : TEST_Op<"str_enum_attr"> {
219  let arguments = (ins SomeStrEnum:$attr);
220  let results = (outs I32:$val);
221}
222
223def I32Case5:  I32EnumAttrCase<"case5", 5>;
224def I32Case10: I32EnumAttrCase<"case10", 10>;
225
226def SomeI32Enum: I32EnumAttr<
227  "SomeI32Enum", "", [I32Case5, I32Case10]>;
228
229def I32EnumAttrOp : TEST_Op<"i32_enum_attr"> {
230  let arguments = (ins SomeI32Enum:$attr);
231  let results = (outs I32:$val);
232}
233
234def I64Case5:  I64EnumAttrCase<"case5", 5>;
235def I64Case10: I64EnumAttrCase<"case10", 10>;
236
237def SomeI64Enum: I64EnumAttr<
238  "SomeI64Enum", "", [I64Case5, I64Case10]>;
239
240def I64EnumAttrOp : TEST_Op<"i64_enum_attr"> {
241  let arguments = (ins SomeI64Enum:$attr);
242  let results = (outs I32:$val);
243}
244
245def SomeStructAttr : StructAttr<"SomeStructAttr", Test_Dialect, [
246  StructFieldAttr<"some_field", I64Attr>,
247  StructFieldAttr<"some_other_field", I64Attr>
248]> {}
249
250def StructAttrOp : TEST_Op<"struct_attr"> {
251  let arguments = (ins SomeStructAttr:$the_struct_attr);
252  let results = (outs);
253}
254
255def IntAttrOp : TEST_Op<"int_attrs"> {
256  let arguments = (ins
257    AnyI32Attr:$any_i32_attr,
258    IndexAttr:$index_attr,
259    UI32Attr:$ui32_attr,
260    SI32Attr:$si32_attr
261  );
262}
263
264def FloatElementsAttrOp : TEST_Op<"float_elements_attr"> {
265  let arguments = (ins
266      RankedF32ElementsAttr<[2]>:$scalar_f32_attr,
267      RankedF64ElementsAttr<[4, 8]>:$tensor_f64_attr
268  );
269}
270
271// A pattern that updates dense<[3.0, 4.0]> to dense<[5.0, 6.0]>.
272// This tests both matching and generating float elements attributes.
273def UpdateFloatElementsAttr : Pat<
274  (FloatElementsAttrOp
275    ConstantAttr<RankedF32ElementsAttr<[2]>, "{3.0f, 4.0f}">:$f32attr,
276    $f64attr),
277  (FloatElementsAttrOp
278    ConstantAttr<RankedF32ElementsAttr<[2]>, "{5.0f, 6.0f}">:$f32attr,
279    $f64attr)>;
280
281def IntElementsAttrOp : TEST_Op<"int_elements_attr"> {
282  let arguments = (ins
283      AnyI32ElementsAttr:$any_i32_attr,
284      I32ElementsAttr:$i32_attr
285  );
286}
287
288def RankedIntElementsAttrOp : TEST_Op<"ranked_int_elements_attr"> {
289  let arguments = (ins
290      RankedI32ElementsAttr<[2]>:$vector_i32_attr,
291      RankedI64ElementsAttr<[4, 8]>:$matrix_i64_attr
292  );
293}
294
295def DerivedTypeAttrOp : TEST_Op<"derived_type_attr", []> {
296  let results = (outs AnyTensor:$output);
297  DerivedTypeAttr element_dtype =
298    DerivedTypeAttr<"return getElementTypeOrSelf(output().getType());">;
299  DerivedAttr size = DerivedAttr<"int",
300    "return output().getType().cast<ShapedType>().getSizeInBits();",
301    "$_builder.getI32IntegerAttr($_self)">;
302}
303
304def StringElementsAttrOp : TEST_Op<"string_elements_attr"> {
305  let arguments = (ins
306      StringElementsAttr:$scalar_string_attr
307  );
308}
309
310//===----------------------------------------------------------------------===//
311// Test Attribute Constraints
312//===----------------------------------------------------------------------===//
313
314def SymbolRefOp : TEST_Op<"symbol_ref_attr"> {
315  let arguments = (ins
316    Confined<FlatSymbolRefAttr, [ReferToOp<"FuncOp">]>:$symbol
317  );
318}
319
320//===----------------------------------------------------------------------===//
321// Test Regions
322//===----------------------------------------------------------------------===//
323
324def OneRegionOp : TEST_Op<"one_region_op", []> {
325  let regions = (region AnyRegion);
326}
327
328def TwoRegionOp : TEST_Op<"two_region_op", []> {
329  let regions = (region AnyRegion, AnyRegion);
330}
331
332def SizedRegionOp : TEST_Op<"sized_region_op", []> {
333  let regions = (region SizedRegion<2>:$my_region, SizedRegion<1>);
334}
335
336//===----------------------------------------------------------------------===//
337// NoTerminator Operation
338//===----------------------------------------------------------------------===//
339
340def SingleNoTerminatorOp : TEST_Op<"single_no_terminator_op", GraphRegionNoTerminator.traits> {
341  let regions = (region SizedRegion<1>:$my_region);
342
343  let assemblyFormat = "attr-dict `:` $my_region";
344}
345
346def VariadicNoTerminatorOp : TEST_Op<"variadic_no_terminator_op", GraphRegionNoTerminator.traits> {
347  let regions = (region VariadicRegion<SizedRegion<1>>:$my_regions);
348
349  let assemblyFormat = "attr-dict `:` $my_regions";
350}
351
352//===----------------------------------------------------------------------===//
353// Test Call Interfaces
354//===----------------------------------------------------------------------===//
355
356def ConversionCallOp : TEST_Op<"conversion_call_op",
357    [CallOpInterface]> {
358  let arguments = (ins Variadic<AnyType>:$inputs, SymbolRefAttr:$callee);
359  let results = (outs Variadic<AnyType>);
360
361  let extraClassDeclaration = [{
362    /// Get the argument operands to the called function.
363    operand_range getArgOperands() { return inputs(); }
364
365    /// Return the callee of this operation.
366    CallInterfaceCallable getCallableForCallee() {
367      return (*this)->getAttrOfType<SymbolRefAttr>("callee");
368    }
369  }];
370}
371
372def FunctionalRegionOp : TEST_Op<"functional_region_op",
373    [CallableOpInterface]> {
374  let regions = (region AnyRegion:$body);
375  let results = (outs FunctionType);
376
377  let extraClassDeclaration = [{
378    Region *getCallableRegion() { return &body(); }
379    ArrayRef<Type> getCallableResults() {
380      return getType().cast<FunctionType>().getResults();
381    }
382  }];
383}
384
385
386def FoldToCallOp : TEST_Op<"fold_to_call_op"> {
387  let arguments = (ins FlatSymbolRefAttr:$callee);
388  let hasCanonicalizer = 1;
389}
390
391//===----------------------------------------------------------------------===//
392// Test Traits
393//===----------------------------------------------------------------------===//
394
395def SameOperandElementTypeOp : TEST_Op<"same_operand_element_type",
396    [SameOperandsElementType]> {
397  let arguments = (ins AnyType, AnyType);
398  let results = (outs AnyType);
399}
400
401def SameOperandAndResultElementTypeOp :
402    TEST_Op<"same_operand_and_result_element_type",
403    [SameOperandsAndResultElementType]> {
404  let arguments = (ins Variadic<AnyType>);
405  let results = (outs Variadic<AnyType>);
406}
407
408def SameOperandShapeOp : TEST_Op<"same_operand_shape", [SameOperandsShape]> {
409  let arguments = (ins Variadic<AnyShaped>);
410}
411
412def SameOperandAndResultShapeOp : TEST_Op<"same_operand_and_result_shape",
413    [SameOperandsAndResultShape]> {
414  let arguments = (ins Variadic<AnyShaped>);
415  let results = (outs Variadic<AnyShaped>);
416}
417
418def SameOperandAndResultTypeOp : TEST_Op<"same_operand_and_result_type",
419    [SameOperandsAndResultType]> {
420  let arguments = (ins Variadic<AnyType>);
421  let results = (outs Variadic<AnyType>);
422}
423
424def ElementwiseMappableOp : TEST_Op<"elementwise_mappable",
425    ElementwiseMappable.traits> {
426  let arguments = (ins Variadic<AnyType>);
427  let results = (outs Variadic<AnyType>);
428}
429
430def ArgAndResHaveFixedElementTypesOp :
431    TEST_Op<"arg_and_res_have_fixed_element_types",
432      [PredOpTrait<"fixed type combination",
433         And<[ElementTypeIsPred<"x", I32>,
434              ElementTypeIsPred<"y", F32>]>>,
435      ElementTypeIs<"res", I16>]> {
436  let arguments = (ins
437    AnyShaped:$x, AnyShaped:$y);
438  let results = (outs AnyShaped:$res);
439}
440
441def OperandsHaveSameElementType : TEST_Op<"operands_have_same_element_type", [
442    AllElementTypesMatch<["x", "y"]>]> {
443  let arguments = (ins AnyType:$x, AnyType:$y);
444}
445
446def OperandZeroAndResultHaveSameElementType : TEST_Op<
447    "operand0_and_result_have_same_element_type",
448    [AllElementTypesMatch<["x", "res"]>]> {
449  let arguments = (ins AnyType:$x, AnyType:$y);
450  let results = (outs AnyType:$res);
451}
452
453def OperandsHaveSameType :
454    TEST_Op<"operands_have_same_type", [AllTypesMatch<["x", "y"]>]> {
455  let arguments = (ins AnyType:$x, AnyType:$y);
456}
457
458def ResultHasSameTypeAsAttr :
459    TEST_Op<"result_has_same_type_as_attr",
460            [AllTypesMatch<["attr", "result"]>]> {
461  let arguments = (ins AnyAttr:$attr);
462  let results = (outs AnyType:$result);
463  let assemblyFormat = "$attr `->` type($result) attr-dict";
464}
465
466def OperandZeroAndResultHaveSameType :
467    TEST_Op<"operand0_and_result_have_same_type",
468            [AllTypesMatch<["x", "res"]>]> {
469  let arguments = (ins AnyType:$x, AnyType:$y);
470  let results = (outs AnyType:$res);
471}
472
473def OperandsHaveSameRank :
474    TEST_Op<"operands_have_same_rank", [AllRanksMatch<["x", "y"]>]> {
475  let arguments = (ins AnyShaped:$x, AnyShaped:$y);
476}
477
478def OperandZeroAndResultHaveSameRank :
479    TEST_Op<"operand0_and_result_have_same_rank",
480            [AllRanksMatch<["x", "res"]>]> {
481  let arguments = (ins AnyShaped:$x, AnyShaped:$y);
482  let results = (outs AnyShaped:$res);
483}
484
485def OperandZeroAndResultHaveSameShape :
486    TEST_Op<"operand0_and_result_have_same_shape",
487            [AllShapesMatch<["x", "res"]>]> {
488  let arguments = (ins AnyShaped:$x, AnyShaped:$y);
489  let results = (outs AnyShaped:$res);
490}
491
492def OperandZeroAndResultHaveSameElementCount :
493    TEST_Op<"operand0_and_result_have_same_element_count",
494            [AllElementCountsMatch<["x", "res"]>]> {
495  let arguments = (ins AnyShaped:$x, AnyShaped:$y);
496  let results = (outs AnyShaped:$res);
497}
498
499def FourEqualsFive :
500    TEST_Op<"four_equals_five", [AllMatch<["5", "4"], "4 equals 5">]>;
501
502def OperandRankEqualsResultSize :
503    TEST_Op<"operand_rank_equals_result_size",
504            [AllMatch<[Rank<"operand">.result, ElementCount<"result">.result],
505                      "operand rank equals result size">]> {
506  let arguments = (ins AnyShaped:$operand);
507  let results = (outs AnyShaped:$result);
508}
509
510def IfFirstOperandIsNoneThenSoIsSecond :
511    TEST_Op<"if_first_operand_is_none_then_so_is_second", [PredOpTrait<
512    "has either both none type operands or first is not none",
513     Or<[
514        And<[TypeIsPred<"x", NoneType>, TypeIsPred<"y", NoneType>]>,
515        Neg<TypeIsPred<"x", NoneType>>]>>]> {
516  let arguments = (ins AnyType:$x, AnyType:$y);
517}
518
519def BroadcastableOp : TEST_Op<"broadcastable", [ResultsBroadcastableShape]> {
520  let arguments = (ins Variadic<AnyTensor>);
521  let results = (outs AnyTensor);
522}
523
524// HasParent trait
525def ParentOp : TEST_Op<"parent"> {
526    let regions = (region AnyRegion);
527}
528def ChildOp : TEST_Op<"child", [HasParent<"ParentOp">]>;
529
530// ParentOneOf trait
531def ParentOp1 : TEST_Op<"parent1"> {
532  let regions = (region AnyRegion);
533}
534def ChildWithParentOneOf : TEST_Op<"child_with_parent_one_of",
535                                [ParentOneOf<["ParentOp", "ParentOp1"]>]>;
536
537def TerminatorOp : TEST_Op<"finish", [Terminator]>;
538def SingleBlockImplicitTerminatorOp : TEST_Op<"SingleBlockImplicitTerminator",
539    [SingleBlockImplicitTerminator<"TerminatorOp">]> {
540  let regions = (region SizedRegion<1>:$region);
541}
542
543def I32ElementsAttrOp : TEST_Op<"i32ElementsAttr"> {
544  let arguments = (ins I32ElementsAttr:$attr);
545}
546
547def IndexElementsAttrOp : TEST_Op<"indexElementsAttr"> {
548  let arguments = (ins IndexElementsAttr:$attr);
549}
550
551def OpWithInferTypeInterfaceOp : TEST_Op<"op_with_infer_type_if", [
552    DeclareOpInterfaceMethods<InferTypeOpInterface,
553        ["inferReturnTypeComponents"]>]> {
554  let arguments = (ins AnyTensor, AnyTensor);
555  let results = (outs AnyTensor);
556}
557
558def OpWithShapedTypeInferTypeInterfaceOp : TEST_Op<"op_with_shaped_type_infer_type_if",
559      InferTensorTypeWithReify.traits> {
560  let arguments = (ins AnyTensor, AnyTensor);
561  let results = (outs AnyTensor);
562}
563
564def OpWithResultShapePerDimInterfaceOp : TEST_Op<"op_with_result_shape_per_dim_interface",
565      [DeclareOpInterfaceMethods<InferShapedTypeOpInterface,
566           ["reifyReturnTypeShapesPerResultDim"]>]> {
567  let arguments = (ins AnyRankedTensor:$operand1, AnyRankedTensor:$operand2);
568  let results = (outs AnyRankedTensor:$result1, AnyRankedTensor:$result2);
569}
570
571def IsNotScalar : Constraint<CPred<"$0.getType().getRank() != 0">>;
572
573def UpdateAttr : Pat<(I32ElementsAttrOp $attr),
574                     (I32ElementsAttrOp ConstantAttr<I32ElementsAttr, "0">),
575                     [(IsNotScalar $attr)]>;
576
577def TestBranchOp : TEST_Op<"br",
578    [DeclareOpInterfaceMethods<BranchOpInterface>, Terminator]> {
579  let arguments = (ins Variadic<AnyType>:$targetOperands);
580  let successors = (successor AnySuccessor:$target);
581}
582
583def AttrSizedOperandOp : TEST_Op<"attr_sized_operands",
584                                 [AttrSizedOperandSegments]> {
585  let arguments = (ins
586    Variadic<I32>:$a,
587    Variadic<I32>:$b,
588    I32:$c,
589    Variadic<I32>:$d,
590    I32ElementsAttr:$operand_segment_sizes
591  );
592}
593
594def AttrSizedResultOp : TEST_Op<"attr_sized_results",
595                                [AttrSizedResultSegments]> {
596  let arguments = (ins
597    I32ElementsAttr:$result_segment_sizes
598  );
599  let results = (outs
600    Variadic<I32>:$a,
601    Variadic<I32>:$b,
602    I32:$c,
603    Variadic<I32>:$d
604  );
605}
606
607// This is used to test encoding of a string attribute into an SSA name of a
608// pretty printed value name.
609def StringAttrPrettyNameOp
610 : TEST_Op<"string_attr_pretty_name",
611           [DeclareOpInterfaceMethods<OpAsmOpInterface>]> {
612  let arguments = (ins StrArrayAttr:$names);
613  let results = (outs Variadic<I32>:$r);
614
615  let printer = [{ return ::print(p, *this); }];
616  let parser = [{ return ::parse$cppClass(parser, result); }];
617}
618
619//===----------------------------------------------------------------------===//
620// Test Locations
621//===----------------------------------------------------------------------===//
622
623def TestLocationSrcOp : TEST_Op<"loc_src"> {
624  let arguments = (ins I32:$input);
625  let results = (outs I32:$output);
626}
627
628def TestLocationDstOp : TEST_Op<"loc_dst", [SameOperandsAndResultType]> {
629  let arguments = (ins I32:$input);
630  let results = (outs I32:$output);
631}
632
633//===----------------------------------------------------------------------===//
634// Test Patterns
635//===----------------------------------------------------------------------===//
636
637def OpA : TEST_Op<"op_a"> {
638  let arguments = (ins I32, I32Attr:$attr);
639  let results = (outs I32);
640}
641
642def OpB : TEST_Op<"op_b"> {
643  let arguments = (ins I32, I32Attr:$attr);
644  let results = (outs I32);
645}
646
647// Test named pattern.
648def TestNamedPatternRule : Pat<(OpA $input, $attr), (OpB $input, $attr)>;
649
650// Test with fused location.
651def : Pat<(OpA (OpA $input, $attr), $bttr), (OpB $input, $bttr)>;
652
653// Test added benefit.
654def OpD : TEST_Op<"op_d">, Arguments<(ins I32)>, Results<(outs I32)>;
655def OpE : TEST_Op<"op_e">, Arguments<(ins I32)>, Results<(outs I32)>;
656def OpF : TEST_Op<"op_f">, Arguments<(ins I32)>, Results<(outs I32)>;
657def OpG : TEST_Op<"op_g">, Arguments<(ins I32)>, Results<(outs I32)>;
658// Verify that bumping benefit results in selecting different op.
659def : Pat<(OpD $input), (OpE $input)>;
660def : Pat<(OpD $input), (OpF $input), [], (addBenefit 10)>;
661// Verify that patterns with more source nodes are selected before those with fewer.
662def : Pat<(OpG $input), (OpB $input, ConstantAttr<I32Attr, "20">:$attr)>;
663def : Pat<(OpG (OpG $input)), (OpB $input, ConstantAttr<I32Attr, "34">:$attr)>;
664
665// Test patterns for zero-result op.
666def OpH : TEST_Op<"op_h">, Arguments<(ins I32)>, Results<(outs)>;
667def OpI : TEST_Op<"op_i">, Arguments<(ins I32)>, Results<(outs)>;
668def : Pat<(OpH $input), (OpI $input)>;
669
670// Test patterns for zero-input op.
671def OpJ : TEST_Op<"op_j">, Arguments<(ins)>, Results<(outs I32)>;
672def OpK : TEST_Op<"op_k">, Arguments<(ins)>, Results<(outs I32)>;
673def : Pat<(OpJ), (OpK)>;
674
675// Test that natives calls are only called once during rewrites.
676def OpM : TEST_Op<"op_m"> {
677  let arguments = (ins I32, OptionalAttr<I32Attr>:$optional_attr);
678  let results = (outs I32);
679}
680
681def OpN : TEST_Op<"op_n"> {
682  let arguments = (ins I32, I32);
683  let results = (outs I32);
684}
685
686def OpO : TEST_Op<"op_o"> {
687  let arguments = (ins I32);
688  let results = (outs I32);
689}
690
691def OpP : TEST_Op<"op_p"> {
692  let arguments = (ins I32, I32, I32, I32, I32, I32);
693  let results = (outs I32);
694}
695
696// Test same operand name enforces equality condition check.
697def TestEqualArgsPattern : Pat<(OpN $a, $a), (OpO $a)>;
698
699// Test when equality is enforced at different depth.
700def TestNestedOpEqualArgsPattern :
701  Pat<(OpN $b, (OpP $a, $b, $c, $d, $e, $f)), (replaceWithValue $b)>;
702
703// Test multiple equal arguments check enforced.
704def TestMultipleEqualArgsPattern :
705  Pat<(OpP $a, $b, $a, $a, $b, $c), (OpN $c, $b)>;
706
707// Test for memrefs normalization of an op with normalizable memrefs.
708def OpNorm : TEST_Op<"op_norm", [MemRefsNormalizable]> {
709  let arguments = (ins AnyMemRef:$X, AnyMemRef:$Y);
710}
711// Test for memrefs normalization of an op without normalizable memrefs.
712def OpNonNorm : TEST_Op<"op_nonnorm"> {
713  let arguments = (ins AnyMemRef:$X, AnyMemRef:$Y);
714}
715// Test for memrefs normalization of an op that has normalizable memref results.
716def OpNormRet : TEST_Op<"op_norm_ret", [MemRefsNormalizable]> {
717  let arguments = (ins AnyMemRef:$X);
718  let results = (outs AnyMemRef:$Y, AnyMemRef:$Z);
719}
720
721// Test for memrefs normalization of an op with a reference to a function
722// symbol.
723def OpFuncRef : TEST_Op<"op_funcref"> {
724  let summary = "Test op with a reference to a function symbol";
725  let description = [{
726    The "test.op_funcref" is a test op with a reference to a function symbol.
727  }];
728  let builders = [OpBuilder<(ins "FuncOp":$function)>];
729}
730
731// Pattern add the argument plus a increasing static number hidden in
732// OpMTest function. That value is set into the optional argument.
733// That way, we will know if operations is called once or twice.
734def OpMGetNullAttr : NativeCodeCall<"Attribute()">;
735def OpMAttributeIsNull : Constraint<CPred<"! ($_self)">, "Attribute is null">;
736def OpMVal : NativeCodeCall<"OpMTest($_builder, $0)">;
737def : Pat<(OpM $attr, $optAttr), (OpM $attr, (OpMVal $attr) ),
738    [(OpMAttributeIsNull:$optAttr)]>;
739
740// Test `$_` for ignoring op argument match.
741def TestIgnoreArgMatchSrcOp : TEST_Op<"ignore_arg_match_src"> {
742  let arguments = (ins
743    AnyType:$a, AnyType:$b, AnyType:$c,
744    AnyAttr:$d, AnyAttr:$e, AnyAttr:$f);
745}
746def TestIgnoreArgMatchDstOp : TEST_Op<"ignore_arg_match_dst"> {
747  let arguments = (ins AnyType:$b, AnyAttr:$f);
748}
749def : Pat<(TestIgnoreArgMatchSrcOp $_, $b, I32, I64Attr:$_, $_, $f),
750          (TestIgnoreArgMatchDstOp $b, $f)>;
751
752def OpInterleavedOperandAttribute1 : TEST_Op<"interleaved_operand_attr1"> {
753  let arguments = (ins
754    I32:$input1,
755    I64Attr:$attr1,
756    I32:$input2,
757    I64Attr:$attr2
758  );
759}
760
761def OpInterleavedOperandAttribute2 : TEST_Op<"interleaved_operand_attr2"> {
762  let arguments = (ins
763    I32:$input1,
764    I64Attr:$attr1,
765    I32:$input2,
766    I64Attr:$attr2
767  );
768}
769
770def ManyArgsOp : TEST_Op<"many_arguments"> {
771  let arguments = (ins
772    I32:$input1, I32:$input2, I32:$input3, I32:$input4, I32:$input5,
773    I32:$input6, I32:$input7, I32:$input8, I32:$input9,
774    I64Attr:$attr1, I64Attr:$attr2, I64Attr:$attr3, I64Attr:$attr4,
775    I64Attr:$attr5, I64Attr:$attr6, I64Attr:$attr7, I64Attr:$attr8,
776    I64Attr:$attr9
777  );
778}
779
780// Test that DRR does not blow up when seeing lots of arguments.
781def : Pat<(ManyArgsOp
782            $input1, $input2, $input3, $input4, $input5,
783            $input6, $input7, $input8, $input9,
784            ConstantAttr<I64Attr, "42">,
785            $attr2, $attr3, $attr4, $attr5, $attr6,
786            $attr7, $attr8, $attr9),
787          (ManyArgsOp
788            $input1, $input2, $input3, $input4, $input5,
789            $input6, $input7, $input8, $input9,
790            ConstantAttr<I64Attr, "24">,
791            $attr2, $attr3, $attr4, $attr5, $attr6,
792            $attr7, $attr8, $attr9)>;
793
794// Test that we can capture and reference interleaved operands and attributes.
795def : Pat<(OpInterleavedOperandAttribute1 $input1, $attr1, $input2, $attr2),
796          (OpInterleavedOperandAttribute2 $input1, $attr1, $input2, $attr2)>;
797
798// Test NativeCodeCall.
799def OpNativeCodeCall1 : TEST_Op<"native_code_call1"> {
800  let arguments = (ins
801    I32:$input1, I32:$input2,
802    BoolAttr:$choice,
803    I64Attr:$attr1, I64Attr:$attr2
804  );
805  let results = (outs I32);
806}
807def OpNativeCodeCall2 : TEST_Op<"native_code_call2"> {
808  let arguments = (ins I32:$input, I64ArrayAttr:$attr);
809  let results = (outs I32);
810}
811// Native code call to invoke a C++ function
812def CreateOperand: NativeCodeCall<"chooseOperand($0, $1, $2)">;
813// Native code call to invoke a C++ expression
814def CreateArrayAttr: NativeCodeCall<"$_builder.getArrayAttr({$0, $1})">;
815// Test that we can use NativeCodeCall to create operand and attribute.
816// This pattern chooses between $input1 and $input2 according to $choice and
817// it combines $attr1 and $attr2 into an array attribute.
818def : Pat<(OpNativeCodeCall1 $input1, $input2,
819                             ConstBoolAttrTrue:$choice, $attr1, $attr2),
820          (OpNativeCodeCall2 (CreateOperand $input1, $input2, $choice),
821                             (CreateArrayAttr $attr1, $attr2))>;
822// Note: the following is just for testing purpose.
823// Should use the replaceWithValue directive instead.
824def UseOpResult: NativeCodeCall<"$0">;
825// Test that we can use NativeCodeCall to create result.
826def : Pat<(OpNativeCodeCall1 $input1, $input2,
827                             ConstBoolAttrFalse, $attr1, $attr2),
828          (UseOpResult $input2)>;
829
830def OpNativeCodeCall3 : TEST_Op<"native_code_call3"> {
831  let arguments = (ins I32:$input);
832  let results = (outs I32);
833}
834// Test that NativeCodeCall is not ignored if it is not used to directly
835// replace the matched root op.
836def : Pattern<(OpNativeCodeCall3 $input),
837              [(NativeCodeCall<"createOpI($_builder, $_loc, $0)"> $input),
838               (OpK)]>;
839
840def OpNativeCodeCall4 : TEST_Op<"native_code_call4"> {
841  let arguments = (ins AnyType:$input1);
842  let results = (outs I32:$output1, I32:$output2);
843}
844def OpNativeCodeCall5 : TEST_Op<"native_code_call5"> {
845  let arguments = (ins I32:$input1, I32:$input2);
846  let results = (outs I32:$output1, I32:$output2);
847}
848
849def GetFirstI32Result : NativeCodeCall<"success(getFirstI32Result($_self, $0))">;
850def BindNativeCodeCallResult : NativeCodeCall<"bindNativeCodeCallResult($0)">;
851def : Pat<(OpNativeCodeCall4 (GetFirstI32Result $ret)),
852          (OpNativeCodeCall5 (BindNativeCodeCallResult:$native $ret), $native)>;
853
854// Test AllAttrConstraintsOf.
855def OpAllAttrConstraint1 : TEST_Op<"all_attr_constraint_of1"> {
856  let arguments = (ins I64ArrayAttr:$attr);
857  let results = (outs I32);
858}
859def OpAllAttrConstraint2 : TEST_Op<"all_attr_constraint_of2"> {
860  let arguments = (ins I64ArrayAttr:$attr);
861  let results = (outs I32);
862}
863def Constraint0 : AttrConstraint<
864    CPred<"$_self.cast<ArrayAttr>()[0]."
865          "cast<IntegerAttr>().getInt() == 0">,
866    "[0] == 0">;
867def Constraint1 : AttrConstraint<
868    CPred<"$_self.cast<ArrayAttr>()[1].cast<IntegerAttr>().getInt() == 1">,
869    "[1] == 1">;
870def : Pat<(OpAllAttrConstraint1
871            AllAttrConstraintsOf<[Constraint0, Constraint1]>:$attr),
872          (OpAllAttrConstraint2 $attr)>;
873
874// Op for testing RewritePattern removing op with inner ops.
875def TestOpWithRegionPattern : TEST_Op<"op_with_region_pattern"> {
876  let regions = (region SizedRegion<1>:$region);
877  let hasCanonicalizer = 1;
878}
879
880def TestOpConstant : TEST_Op<"constant", [ConstantLike, NoSideEffect]> {
881  let arguments = (ins AnyAttr:$value);
882  let results = (outs AnyType);
883  let extraClassDeclaration = [{
884    Attribute getValue() { return (*this)->getAttr("value"); }
885  }];
886
887  let hasFolder = 1;
888}
889
890def OpR : TEST_Op<"op_r">, Arguments<(ins AnyInteger, AnyInteger)>, Results<(outs AnyInteger)>;
891def OpS : TEST_Op<"op_s">, Arguments<(ins AnyInteger, AnyAttr:$value)>, Results<(outs AnyInteger)>;
892
893def : Pat<(OpR $input1, (ConstantLikeMatcher I32Attr:$input2)),
894          (OpS:$unused $input1, $input2)>;
895
896// Op for testing trivial removal via folding of op with inner ops and no uses.
897def TestOpWithRegionFoldNoSideEffect : TEST_Op<
898    "op_with_region_fold_no_side_effect", [NoSideEffect]> {
899  let regions = (region SizedRegion<1>:$region);
900}
901
902// Op for testing folding of outer op with inner ops.
903def TestOpWithRegionFold : TEST_Op<"op_with_region_fold"> {
904  let arguments = (ins I32:$operand);
905  let results = (outs I32);
906  let regions = (region SizedRegion<1>:$region);
907  let hasFolder = 1;
908}
909
910def TestOpWithVariadicResultsAndFolder: TEST_Op<"op_with_variadic_results_and_folder"> {
911  let arguments = (ins Variadic<I32>:$operands);
912  let results = (outs Variadic<I32>);
913  let hasFolder = 1;
914}
915
916def TestCommutativeOp : TEST_Op<"op_commutative", [Commutative]> {
917  let arguments = (ins I32:$op1, I32:$op2, I32:$op3, I32:$op4);
918  let results = (outs I32);
919}
920
921def TestIdempotentTraitOp
922 : TEST_Op<"op_idempotent_trait",
923           [SameOperandsAndResultType, NoSideEffect, Idempotent]> {
924  let arguments = (ins I32:$op1);
925  let results = (outs I32);
926}
927
928def TestInvolutionTraitNoOperationFolderOp
929 : TEST_Op<"op_involution_trait_no_operation_fold",
930           [SameOperandsAndResultType, NoSideEffect, Involution]> {
931  let arguments = (ins I32:$op1);
932  let results = (outs I32);
933}
934
935def TestInvolutionTraitFailingOperationFolderOp
936 : TEST_Op<"op_involution_trait_failing_operation_fold",
937           [SameOperandsAndResultType, NoSideEffect, Involution]> {
938  let arguments = (ins I32:$op1);
939  let results = (outs I32);
940  let hasFolder = 1;
941}
942
943def TestInvolutionTraitSuccesfulOperationFolderOp
944 : TEST_Op<"op_involution_trait_succesful_operation_fold",
945           [SameOperandsAndResultType, NoSideEffect, Involution]> {
946  let arguments = (ins I32:$op1);
947  let results = (outs I32);
948  let hasFolder = 1;
949}
950
951def TestOpInPlaceFoldAnchor : TEST_Op<"op_in_place_fold_anchor"> {
952  let arguments = (ins I32);
953  let results = (outs I32);
954}
955
956def TestOpInPlaceFold : TEST_Op<"op_in_place_fold"> {
957  let arguments = (ins I32:$op, I32Attr:$attr);
958  let results = (outs I32);
959  let hasFolder = 1;
960}
961
962// An op that always fold itself.
963def TestPassthroughFold : TEST_Op<"passthrough_fold"> {
964  let arguments = (ins AnyType:$op);
965  let results = (outs AnyType);
966  let hasFolder = 1;
967}
968
969//===----------------------------------------------------------------------===//
970// Test Patterns (Symbol Binding)
971
972// Test symbol binding.
973def OpSymbolBindingA : TEST_Op<"symbol_binding_a", []> {
974  let arguments = (ins I32:$operand, I64Attr:$attr);
975  let results = (outs I32);
976}
977def OpSymbolBindingB : TEST_Op<"symbol_binding_b", []> {
978  let arguments = (ins I32:$operand);
979  let results = (outs I32);
980}
981def OpSymbolBindingC : TEST_Op<"symbol_binding_c", []> {
982  let arguments = (ins I32:$operand);
983  let results = (outs I32);
984  let builders = OpSymbolBindingB.builders;
985}
986def OpSymbolBindingD : TEST_Op<"symbol_binding_d", []> {
987  let arguments = (ins I32:$input1, I32:$input2, I64Attr:$attr);
988  let results = (outs I32);
989}
990def HasOneUse: Constraint<CPred<"$0.hasOneUse()">, "has one use">;
991def : Pattern<
992    // Bind to source pattern op operand/attribute/result
993    (OpSymbolBindingA:$res_a $operand, $attr), [
994        // Bind to auxiliary op result
995        (OpSymbolBindingC:$res_c (OpSymbolBindingB:$res_b $operand)),
996
997        // Use bound symbols in resultant ops
998        (OpSymbolBindingD $res_b, $res_c, $attr)],
999    // Use bound symbols in additional constraints
1000    [(HasOneUse $res_a)]>;
1001
1002def OpSymbolBindingNoResult : TEST_Op<"symbol_binding_no_result", []> {
1003  let arguments = (ins I32:$operand);
1004}
1005
1006// Test that we can bind to an op without results and reference it later.
1007def : Pat<(OpSymbolBindingNoResult:$op $operand),
1008          (NativeCodeCall<"handleNoResultOp($_builder, $0)"> $op)>;
1009
1010//===----------------------------------------------------------------------===//
1011// Test Patterns (Attributes)
1012
1013// Test matching against op attributes.
1014def OpAttrMatch1 : TEST_Op<"match_op_attribute1"> {
1015  let arguments = (ins
1016    I32Attr:$required_attr,
1017    OptionalAttr<I32Attr>:$optional_attr,
1018    DefaultValuedAttr<I32Attr, "42">:$default_valued_attr,
1019    I32Attr:$more_attr
1020  );
1021  let results = (outs I32);
1022}
1023def OpAttrMatch2 : TEST_Op<"match_op_attribute2"> {
1024  let arguments = OpAttrMatch1.arguments;
1025  let results = (outs I32);
1026}
1027def MoreConstraint : AttrConstraint<
1028    CPred<"$_self.cast<IntegerAttr>().getInt() == 4">, "more constraint">;
1029def : Pat<(OpAttrMatch1 $required, $optional, $default_valued,
1030                        MoreConstraint:$more),
1031          (OpAttrMatch2 $required, $optional, $default_valued, $more)>;
1032
1033// Test unit attrs.
1034def OpAttrMatch3 : TEST_Op<"match_op_attribute3"> {
1035  let arguments = (ins UnitAttr:$attr);
1036  let results = (outs I32);
1037}
1038def OpAttrMatch4 : TEST_Op<"match_op_attribute4"> {
1039  let arguments = (ins UnitAttr:$attr1, UnitAttr:$attr2);
1040  let results = (outs I32);
1041}
1042def : Pat<(OpAttrMatch3 $attr), (OpAttrMatch4 ConstUnitAttr, $attr)>;
1043
1044// Test with constant attr.
1045def OpC : TEST_Op<"op_c">, Arguments<(ins I32)>, Results<(outs I32)>;
1046def : Pat<(OpC $input), (OpB $input, ConstantAttr<I32Attr, "17">:$attr)>;
1047
1048// Test string enum attribute in rewrites.
1049def : Pat<(StrEnumAttrOp StrCaseA), (StrEnumAttrOp StrCaseB)>;
1050// Test integer enum attribute in rewrites.
1051def : Pat<(I32EnumAttrOp I32Case5), (I32EnumAttrOp I32Case10)>;
1052def : Pat<(I64EnumAttrOp I64Case5), (I64EnumAttrOp I64Case10)>;
1053
1054//===----------------------------------------------------------------------===//
1055// Test Patterns (Multi-result Ops)
1056
1057def MultiResultOpKind1: I64EnumAttrCase<"kind1", 1>;
1058def MultiResultOpKind2: I64EnumAttrCase<"kind2", 2>;
1059def MultiResultOpKind3: I64EnumAttrCase<"kind3", 3>;
1060def MultiResultOpKind4: I64EnumAttrCase<"kind4", 4>;
1061def MultiResultOpKind5: I64EnumAttrCase<"kind5", 5>;
1062def MultiResultOpKind6: I64EnumAttrCase<"kind6", 6>;
1063
1064def MultiResultOpEnum: I64EnumAttr<
1065  "MultiResultOpEnum", "Multi-result op kinds", [
1066    MultiResultOpKind1, MultiResultOpKind2, MultiResultOpKind3,
1067    MultiResultOpKind4, MultiResultOpKind5, MultiResultOpKind6
1068  ]>;
1069
1070def ThreeResultOp : TEST_Op<"three_result"> {
1071  let arguments = (ins MultiResultOpEnum:$kind);
1072  let results = (outs I32:$result1, F32:$result2, F32:$result3);
1073}
1074
1075def AnotherThreeResultOp : TEST_Op<"another_three_result", [DeclareOpInterfaceMethods<InferTypeOpInterface>]> {
1076  let arguments = (ins MultiResultOpEnum:$kind);
1077  let results = (outs I32:$result1, F32:$result2, F32:$result3);
1078}
1079
1080def TwoResultOp : TEST_Op<"two_result"> {
1081  let arguments = (ins MultiResultOpEnum:$kind);
1082  let results = (outs I32:$result1, F32:$result2);
1083}
1084
1085def AnotherTwoResultOp : TEST_Op<"another_two_result"> {
1086  let arguments = (ins MultiResultOpEnum:$kind);
1087  let results = (outs F32:$result1, F32:$result2);
1088}
1089
1090def OneResultOp1 : TEST_Op<"one_result1"> {
1091  let arguments = (ins MultiResultOpEnum:$kind);
1092  let results = (outs F32:$result1);
1093}
1094
1095def OneResultOp2 : TEST_Op<"one_result2"> {
1096  let arguments = (ins MultiResultOpEnum:$kind);
1097  let results = (outs I32:$result1);
1098}
1099
1100def OneResultOp3 : TEST_Op<"one_result3"> {
1101  let arguments = (ins F32);
1102  let results = (outs I32:$result1);
1103}
1104
1105// Test using multi-result op as a whole
1106def : Pat<(ThreeResultOp MultiResultOpKind1:$kind),
1107          (AnotherThreeResultOp $kind)>;
1108
1109// Test using multi-result op as a whole for partial replacement
1110def : Pattern<(ThreeResultOp MultiResultOpKind2:$kind),
1111              [(TwoResultOp $kind),
1112               (OneResultOp1 $kind)]>;
1113def : Pattern<(ThreeResultOp MultiResultOpKind3:$kind),
1114              [(OneResultOp2 $kind),
1115               (AnotherTwoResultOp $kind)]>;
1116
1117// Test using results separately in a multi-result op
1118def : Pattern<(ThreeResultOp MultiResultOpKind4:$kind),
1119              [(TwoResultOp:$res1__0 $kind),
1120               (OneResultOp1 $kind),
1121               (TwoResultOp:$res2__1 $kind)]>;
1122
1123// Test referencing a single value in the value pack
1124// This rule only matches TwoResultOp if its second result has no use.
1125def : Pattern<(TwoResultOp:$res MultiResultOpKind5:$kind),
1126              [(OneResultOp2 $kind),
1127               (OneResultOp1 $kind)],
1128              [(HasNoUseOf:$res__1)]>;
1129
1130// Test using auxiliary ops for replacing multi-result op
1131def : Pattern<
1132    (ThreeResultOp MultiResultOpKind6:$kind), [
1133        // Auxiliary op generated to help building the final result but not
1134        // directly used to replace the source op's results.
1135        (TwoResultOp:$interm $kind),
1136
1137        (OneResultOp3 $interm__1),
1138        (AnotherTwoResultOp $kind)
1139    ]>;
1140
1141//===----------------------------------------------------------------------===//
1142// Test Patterns (Variadic Ops)
1143
1144def OneVResOneVOperandOp1 : TEST_Op<"one_variadic_out_one_variadic_in1"> {
1145  let arguments = (ins Variadic<I32>);
1146  let results = (outs Variadic<I32>);
1147}
1148def OneVResOneVOperandOp2 : TEST_Op<"one_variadic_out_one_variadic_in2"> {
1149  let arguments = (ins Variadic<I32>);
1150  let results = (outs Variadic<I32>);
1151}
1152
1153// Rewrite an op with one variadic operand and one variadic result to
1154// another similar op.
1155def : Pat<(OneVResOneVOperandOp1 $inputs), (OneVResOneVOperandOp2 $inputs)>;
1156
1157def MixedVOperandOp1 : TEST_Op<"mixed_variadic_in1",
1158                               [SameVariadicOperandSize]> {
1159  let arguments = (ins
1160    Variadic<I32>:$input1,
1161    F32:$input2,
1162    Variadic<I32>:$input3
1163  );
1164}
1165
1166def MixedVOperandOp2 : TEST_Op<"mixed_variadic_in2",
1167                               [SameVariadicOperandSize]> {
1168  let arguments = (ins
1169    Variadic<I32>:$input1,
1170    F32:$input2,
1171    Variadic<I32>:$input3
1172  );
1173}
1174
1175// Rewrite an op with both variadic operands and normal operands.
1176def : Pat<(MixedVOperandOp1 $input1, $input2, $input3),
1177          (MixedVOperandOp2 $input1, $input2, $input3)>;
1178
1179def MixedVResultOp1 : TEST_Op<"mixed_variadic_out1", [SameVariadicResultSize]> {
1180  let results = (outs
1181    Variadic<I32>:$output1,
1182    F32:$output2,
1183    Variadic<I32>:$output3
1184  );
1185}
1186
1187def MixedVResultOp2 : TEST_Op<"mixed_variadic_out2", [SameVariadicResultSize]> {
1188  let results = (outs
1189    Variadic<I32>:$output1,
1190    F32:$output2,
1191    Variadic<I32>:$output3
1192  );
1193}
1194
1195// Rewrite an op with both variadic results and normal results.
1196// Note that because we are generating the op with a top-level result pattern,
1197// we are able to deduce the correct result types for the generated op using
1198// the information from the matched root op.
1199def : Pat<(MixedVResultOp1), (MixedVResultOp2)>;
1200
1201def OneI32ResultOp : TEST_Op<"one_i32_out"> {
1202  let results = (outs I32);
1203}
1204
1205def MixedVOperandOp3 : TEST_Op<"mixed_variadic_in3",
1206                               [SameVariadicOperandSize]> {
1207  let arguments = (ins
1208    I32:$input1,
1209    Variadic<I32>:$input2,
1210    Variadic<I32>:$input3,
1211    I32Attr:$count
1212  );
1213
1214  let results = (outs I32);
1215}
1216
1217def MixedVResultOp3 : TEST_Op<"mixed_variadic_out3",
1218                               [SameVariadicResultSize]> {
1219  let arguments = (ins I32Attr:$count);
1220
1221  let results = (outs
1222    I32:$output1,
1223    Variadic<I32>:$output2,
1224    Variadic<I32>:$output3
1225  );
1226
1227  // We will use this op in a nested result pattern, where we cannot deduce the
1228  // result type. So need to provide a builder not requiring result types.
1229  let builders = [
1230    OpBuilder<(ins "IntegerAttr":$count),
1231    [{
1232      auto i32Type = $_builder.getIntegerType(32);
1233      $_state.addTypes(i32Type); // $output1
1234      SmallVector<Type, 4> types(count.getInt(), i32Type);
1235      $_state.addTypes(types); // $output2
1236      $_state.addTypes(types); // $output3
1237      $_state.addAttribute("count", count);
1238    }]>
1239  ];
1240}
1241
1242// Generates an op with variadic results using nested pattern.
1243def : Pat<(OneI32ResultOp),
1244          (MixedVOperandOp3
1245              (MixedVResultOp3:$results__0 ConstantAttr<I32Attr, "2">),
1246              (replaceWithValue $results__1),
1247              (replaceWithValue $results__2),
1248              ConstantAttr<I32Attr, "2">)>;
1249
1250//===----------------------------------------------------------------------===//
1251// Test Patterns (Location)
1252
1253// Test that we can specify locations for generated ops.
1254def : Pat<(TestLocationSrcOp:$res1
1255           (TestLocationSrcOp:$res2
1256            (TestLocationSrcOp:$res3 $input))),
1257          (TestLocationDstOp
1258            (TestLocationDstOp
1259              (TestLocationDstOp $input, (location $res1)),
1260              (location "named")),
1261            (location "fused", $res2, $res3))>;
1262
1263//===----------------------------------------------------------------------===//
1264// Test Legalization
1265//===----------------------------------------------------------------------===//
1266
1267def Test_LegalizerEnum_Success : StrEnumAttrCase<"Success">;
1268def Test_LegalizerEnum_Failure : StrEnumAttrCase<"Failure">;
1269
1270def Test_LegalizerEnum : StrEnumAttr<"Success", "Failure",
1271  [Test_LegalizerEnum_Success, Test_LegalizerEnum_Failure]>;
1272
1273def ILLegalOpA : TEST_Op<"illegal_op_a">, Results<(outs I32)>;
1274def ILLegalOpB : TEST_Op<"illegal_op_b">, Results<(outs I32)>;
1275def ILLegalOpC : TEST_Op<"illegal_op_c">, Results<(outs I32)>;
1276def ILLegalOpD : TEST_Op<"illegal_op_d">, Results<(outs I32)>;
1277def ILLegalOpE : TEST_Op<"illegal_op_e">, Results<(outs I32)>;
1278def ILLegalOpF : TEST_Op<"illegal_op_f">, Results<(outs I32)>;
1279def LegalOpA : TEST_Op<"legal_op_a">,
1280  Arguments<(ins Test_LegalizerEnum:$status)>, Results<(outs I32)>;
1281def LegalOpB : TEST_Op<"legal_op_b">, Results<(outs I32)>;
1282
1283// Check that the conversion infrastructure can properly undo the creation of
1284// operations where an operation was created before its parent, in this case,
1285// in the parent's builder.
1286def IllegalOpTerminator : TEST_Op<"illegal_op_terminator", [Terminator]>;
1287def IllegalOpWithRegion : TEST_Op<"illegal_op_with_region"> {
1288  let skipDefaultBuilders = 1;
1289  let builders = [OpBuilder<(ins),
1290    [{
1291       Region *bodyRegion = $_state.addRegion();
1292       OpBuilder::InsertionGuard g($_builder);
1293       Block *body = $_builder.createBlock(bodyRegion);
1294       $_builder.setInsertionPointToEnd(body);
1295       $_builder.create<IllegalOpTerminator>($_state.location);
1296    }]>];
1297}
1298def IllegalOpWithRegionAnchor : TEST_Op<"illegal_op_with_region_anchor">;
1299
1300// Check that smaller pattern depths are chosen, i.e. prioritize more direct
1301// mappings.
1302def : Pat<(ILLegalOpA), (LegalOpA Test_LegalizerEnum_Success)>;
1303
1304def : Pat<(ILLegalOpA), (ILLegalOpB)>;
1305def : Pat<(ILLegalOpB), (LegalOpA Test_LegalizerEnum_Failure)>;
1306
1307// Check that the higher benefit pattern is taken for multiple legalizations
1308// with the same depth.
1309def : Pat<(ILLegalOpC), (ILLegalOpD)>;
1310def : Pat<(ILLegalOpD), (LegalOpA Test_LegalizerEnum_Failure)>;
1311
1312def : Pat<(ILLegalOpC), (ILLegalOpE), [], (addBenefit 10)>;
1313def : Pat<(ILLegalOpE), (LegalOpA Test_LegalizerEnum_Success)>;
1314
1315// Check that patterns use the most up-to-date value when being replaced.
1316def TestRewriteOp : TEST_Op<"rewrite">,
1317  Arguments<(ins AnyType)>, Results<(outs AnyType)>;
1318def : Pat<(TestRewriteOp $input), (replaceWithValue $input)>;
1319
1320// Check that patterns can specify bounded recursion when rewriting.
1321def TestRecursiveRewriteOp : TEST_Op<"recursive_rewrite"> {
1322  let arguments = (ins I64Attr:$depth);
1323  let assemblyFormat = "$depth attr-dict";
1324}
1325
1326// Test legalization pattern: this op will be erase and will also erase the
1327// producer of its operand.
1328def BlackHoleOp : TEST_Op<"blackhole">,
1329  Arguments<(ins AnyType)>;
1330
1331//===----------------------------------------------------------------------===//
1332// Test Type Legalization
1333//===----------------------------------------------------------------------===//
1334
1335def TestRegionBuilderOp : TEST_Op<"region_builder">;
1336def TestReturnOp : TEST_Op<"return", [ReturnLike, Terminator]> {
1337  let arguments = (ins Variadic<AnyType>);
1338  let builders = [OpBuilder<(ins),
1339    [{ build($_builder, $_state, {}); }]>
1340  ];
1341}
1342def TestCastOp : TEST_Op<"cast">,
1343  Arguments<(ins Variadic<AnyType>)>, Results<(outs AnyType)>;
1344def TestInvalidOp : TEST_Op<"invalid", [Terminator]>,
1345  Arguments<(ins Variadic<AnyType>)>;
1346def TestTypeProducerOp : TEST_Op<"type_producer">,
1347  Results<(outs AnyType)>;
1348def TestAnotherTypeProducerOp : TEST_Op<"another_type_producer">,
1349  Results<(outs AnyType)>;
1350def TestTypeConsumerOp : TEST_Op<"type_consumer">,
1351  Arguments<(ins AnyType)>;
1352def TestValidOp : TEST_Op<"valid", [Terminator]>,
1353  Arguments<(ins Variadic<AnyType>)>;
1354
1355def TestMergeBlocksOp : TEST_Op<"merge_blocks"> {
1356  let summary = "merge_blocks operation";
1357  let description = [{
1358    Test op with multiple blocks that are merged with Dialect Conversion"
1359  }];
1360
1361  let regions = (region AnyRegion:$body);
1362  let results = (outs Variadic<AnyType>:$result);
1363}
1364
1365def TestSignatureConversionUndoOp : TEST_Op<"signature_conversion_undo"> {
1366  let regions = (region AnyRegion);
1367}
1368
1369//===----------------------------------------------------------------------===//
1370// Test parser.
1371//===----------------------------------------------------------------------===//
1372
1373def ParseIntegerLiteralOp : TEST_Op<"parse_integer_literal"> {
1374  let results = (outs Variadic<Index>:$results);
1375  let parser = [{ return ::parse$cppClass(parser, result); }];
1376  let printer = [{ return ::print(p, *this); }];
1377}
1378
1379def ParseWrappedKeywordOp : TEST_Op<"parse_wrapped_keyword"> {
1380  let arguments = (ins StrAttr:$keyword);
1381  let parser = [{ return ::parse$cppClass(parser, result); }];
1382  let printer = [{ return ::print(p, *this); }];
1383}
1384
1385//===----------------------------------------------------------------------===//
1386// Test region argument list parsing.
1387
1388def IsolatedRegionOp : TEST_Op<"isolated_region", [IsolatedFromAbove]> {
1389  let summary =  "isolated region operation";
1390  let description = [{
1391    Test op with an isolated region, to test passthrough region arguments. Each
1392    argument is of index type.
1393  }];
1394
1395  let arguments = (ins Index);
1396  let regions = (region SizedRegion<1>:$region);
1397  let parser = [{ return ::parse$cppClass(parser, result); }];
1398  let printer = [{ return ::print(p, *this); }];
1399}
1400
1401def SSACFGRegionOp : TEST_Op<"ssacfg_region",  [
1402    DeclareOpInterfaceMethods<RegionKindInterface>]> {
1403  let summary =  "operation with an SSACFG region";
1404  let description = [{
1405    Test op that defines an SSACFG region.
1406  }];
1407
1408  let regions = (region VariadicRegion<AnyRegion>:$regions);
1409  let arguments = (ins Variadic<AnyType>);
1410  let results = (outs Variadic<AnyType>);
1411}
1412
1413def GraphRegionOp : TEST_Op<"graph_region",  [
1414    DeclareOpInterfaceMethods<RegionKindInterface>]> {
1415  let summary =  "operation with a graph region";
1416  let description = [{
1417    Test op that defines a graph region.
1418  }];
1419
1420  let regions = (region AnyRegion:$region);
1421  let parser = [{ return ::parse$cppClass(parser, result); }];
1422  let printer = [{ return ::print(p, *this); }];
1423}
1424
1425def AffineScopeOp : TEST_Op<"affine_scope", [AffineScope]> {
1426  let summary =  "affine scope operation";
1427  let description = [{
1428    Test op that defines a new affine scope.
1429  }];
1430
1431  let regions = (region SizedRegion<1>:$region);
1432  let parser = [{ return ::parse$cppClass(parser, result); }];
1433  let printer = [{ return ::print(p, *this); }];
1434}
1435
1436def WrappingRegionOp : TEST_Op<"wrapping_region",
1437    [SingleBlockImplicitTerminator<"TestReturnOp">]> {
1438  let summary =  "wrapping region operation";
1439  let description = [{
1440    Test op wrapping another op in a region, to test calling
1441    parseGenericOperation from the custom parser.
1442  }];
1443
1444  let results = (outs Variadic<AnyType>);
1445  let regions = (region SizedRegion<1>:$region);
1446  let parser = [{ return ::parse$cppClass(parser, result); }];
1447  let printer = [{ return ::print(p, *this); }];
1448}
1449
1450def PolyForOp : TEST_Op<"polyfor">
1451{
1452  let summary =  "polyfor operation";
1453  let description = [{
1454    Test op with multiple region arguments, each argument of index type.
1455  }];
1456
1457  let regions = (region SizedRegion<1>:$region);
1458  let parser = [{ return ::parse$cppClass(parser, result); }];
1459}
1460
1461//===----------------------------------------------------------------------===//
1462// Test OpAsmInterface.
1463
1464def AsmInterfaceOp : TEST_Op<"asm_interface_op"> {
1465  let results = (outs AnyType:$first, Variadic<AnyType>:$middle_results,
1466                      AnyType);
1467}
1468
1469def AsmDialectInterfaceOp : TEST_Op<"asm_dialect_interface_op"> {
1470  let results = (outs AnyType);
1471}
1472
1473//===----------------------------------------------------------------------===//
1474// Test Op Asm Format
1475//===----------------------------------------------------------------------===//
1476
1477def FormatLiteralOp : TEST_Op<"format_literal_op"> {
1478  let assemblyFormat = [{
1479    `keyword_$.` `->` `:` `,` `=` `<` `>` `(` `)` `[` `]` `` `(` ` ` `)`
1480    `?` `+` `*` `{` `\n` `}` attr-dict
1481  }];
1482}
1483
1484// Test that we elide attributes that are within the syntax.
1485def FormatAttrOp : TEST_Op<"format_attr_op"> {
1486  let arguments = (ins I64Attr:$attr);
1487  let assemblyFormat = "$attr attr-dict";
1488}
1489
1490// Test that we elide optional attributes that are within the syntax.
1491def FormatOptAttrAOp : TEST_Op<"format_opt_attr_op_a"> {
1492  let arguments = (ins OptionalAttr<I64Attr>:$opt_attr);
1493  let assemblyFormat = "(`(` $opt_attr^ `)` )? attr-dict";
1494}
1495def FormatOptAttrBOp : TEST_Op<"format_opt_attr_op_b"> {
1496  let arguments = (ins OptionalAttr<I64Attr>:$opt_attr);
1497  let assemblyFormat = "($opt_attr^)? attr-dict";
1498}
1499
1500// Test that we format symbol name attributes properly.
1501def FormatSymbolNameAttrOp : TEST_Op<"format_symbol_name_attr_op"> {
1502  let arguments = (ins SymbolNameAttr:$attr);
1503  let assemblyFormat = "$attr attr-dict";
1504}
1505
1506// Test that we format optional symbol name attributes properly.
1507def FormatOptSymbolNameAttrOp : TEST_Op<"format_opt_symbol_name_attr_op"> {
1508  let arguments = (ins OptionalAttr<SymbolNameAttr>:$opt_attr);
1509  let assemblyFormat = "($opt_attr^)? attr-dict";
1510}
1511
1512// Test that we elide attributes that are within the syntax.
1513def FormatAttrDictWithKeywordOp : TEST_Op<"format_attr_dict_w_keyword"> {
1514  let arguments = (ins I64Attr:$attr, OptionalAttr<I64Attr>:$opt_attr);
1515  let assemblyFormat = "attr-dict-with-keyword";
1516}
1517
1518// Test that we don't need to provide types in the format if they are buildable.
1519def FormatBuildableTypeOp : TEST_Op<"format_buildable_type_op"> {
1520  let arguments = (ins I64:$buildable);
1521  let results = (outs I64:$buildable_res);
1522  let assemblyFormat = "$buildable attr-dict";
1523}
1524
1525// Test various mixings of region formatting.
1526class FormatRegionBase<string suffix, string fmt>
1527    : TEST_Op<"format_region_" # suffix # "_op"> {
1528  let regions = (region AnyRegion:$region);
1529  let assemblyFormat = fmt;
1530}
1531def FormatRegionAOp : FormatRegionBase<"a", [{
1532  regions attr-dict
1533}]>;
1534def FormatRegionBOp : FormatRegionBase<"b", [{
1535  $region attr-dict
1536}]>;
1537def FormatRegionCOp : FormatRegionBase<"c", [{
1538  (`region` $region^)? attr-dict
1539}]>;
1540class FormatVariadicRegionBase<string suffix, string fmt>
1541    : TEST_Op<"format_variadic_region_" # suffix # "_op"> {
1542  let regions = (region VariadicRegion<AnyRegion>:$regions);
1543  let assemblyFormat = fmt;
1544}
1545def FormatVariadicRegionAOp : FormatVariadicRegionBase<"a", [{
1546  $regions attr-dict
1547}]>;
1548def FormatVariadicRegionBOp : FormatVariadicRegionBase<"b", [{
1549  ($regions^ `found_regions`)? attr-dict
1550}]>;
1551class FormatRegionImplicitTerminatorBase<string suffix, string fmt>
1552    : TEST_Op<"format_implicit_terminator_region_" # suffix # "_op",
1553              [SingleBlockImplicitTerminator<"TestReturnOp">]> {
1554  let regions = (region AnyRegion:$region);
1555  let assemblyFormat = fmt;
1556}
1557def FormatFormatRegionImplicitTerminatorAOp
1558    : FormatRegionImplicitTerminatorBase<"a", [{
1559  $region attr-dict
1560}]>;
1561
1562// Test various mixings of result type formatting.
1563class FormatResultBase<string suffix, string fmt>
1564    : TEST_Op<"format_result_" # suffix # "_op"> {
1565  let results = (outs I64:$buildable_res, AnyMemRef:$result);
1566  let assemblyFormat = fmt;
1567}
1568def FormatResultAOp : FormatResultBase<"a", [{
1569  type($result) attr-dict
1570}]>;
1571def FormatResultBOp : FormatResultBase<"b", [{
1572  type(results) attr-dict
1573}]>;
1574def FormatResultCOp : FormatResultBase<"c", [{
1575  functional-type($buildable_res, $result) attr-dict
1576}]>;
1577
1578def FormatVariadicResult : TEST_Op<"format_variadic_result"> {
1579  let results = (outs Variadic<I64>:$result);
1580  let assemblyFormat = [{ `:` type($result) attr-dict}];
1581}
1582
1583def FormatMultipleVariadicResults : TEST_Op<"format_multiple_variadic_results",
1584                                            [AttrSizedResultSegments]> {
1585  let results = (outs Variadic<I64>:$result0, Variadic<AnyType>:$result1);
1586  let assemblyFormat = [{
1587    `:` `(` type($result0) `)` `,` `(` type($result1) `)` attr-dict
1588  }];
1589}
1590
1591// Test various mixings of operand type formatting.
1592class FormatOperandBase<string suffix, string fmt>
1593    : TEST_Op<"format_operand_" # suffix # "_op"> {
1594  let arguments = (ins I64:$buildable, AnyMemRef:$operand);
1595  let assemblyFormat = fmt;
1596}
1597
1598def FormatOperandAOp : FormatOperandBase<"a", [{
1599  operands `:` type(operands) attr-dict
1600}]>;
1601def FormatOperandBOp : FormatOperandBase<"b", [{
1602  operands `:` type($operand) attr-dict
1603}]>;
1604def FormatOperandCOp : FormatOperandBase<"c", [{
1605  $buildable `,` $operand `:` type(operands) attr-dict
1606}]>;
1607def FormatOperandDOp : FormatOperandBase<"d", [{
1608  $buildable `,` $operand `:` type($operand) attr-dict
1609}]>;
1610def FormatOperandEOp : FormatOperandBase<"e", [{
1611  $buildable `,` $operand `:` type($buildable) `,` type($operand) attr-dict
1612}]>;
1613
1614def FormatSuccessorAOp : TEST_Op<"format_successor_a_op", [Terminator]> {
1615  let successors = (successor VariadicSuccessor<AnySuccessor>:$targets);
1616  let assemblyFormat = "$targets attr-dict";
1617}
1618
1619def FormatVariadicOperand : TEST_Op<"format_variadic_operand"> {
1620  let arguments = (ins Variadic<I64>:$operand);
1621  let assemblyFormat = [{ $operand `:` type($operand) attr-dict}];
1622}
1623
1624def FormatMultipleVariadicOperands :
1625    TEST_Op<"format_multiple_variadic_operands", [AttrSizedOperandSegments]> {
1626  let arguments = (ins Variadic<I64>:$operand0, Variadic<AnyType>:$operand1);
1627  let assemblyFormat = [{
1628    ` ` `(` $operand0 `)` `,` `(` $operand1 `:` type($operand1) `)` attr-dict
1629  }];
1630}
1631
1632// Test various mixings of optional operand and result type formatting.
1633class FormatOptionalOperandResultOpBase<string suffix, string fmt>
1634    : TEST_Op<"format_optional_operand_result_" # suffix # "_op",
1635              [AttrSizedOperandSegments]> {
1636  let arguments = (ins Optional<I64>:$optional, Variadic<I64>:$variadic);
1637  let results = (outs Optional<I64>:$optional_res);
1638  let assemblyFormat = fmt;
1639}
1640
1641def FormatOptionalOperandResultAOp : FormatOptionalOperandResultOpBase<"a", [{
1642  `(` $optional `:` type($optional) `)` `:` type($optional_res)
1643  (`[` $variadic^ `]`)? attr-dict
1644}]>;
1645
1646def FormatOptionalOperandResultBOp : FormatOptionalOperandResultOpBase<"b", [{
1647  (`(` $optional^ `:` type($optional) `)`)? `:` type($optional_res)
1648  (`[` $variadic^ `]`)? attr-dict
1649}]>;
1650
1651// Test optional result type formatting.
1652class FormatOptionalResultOpBase<string suffix, string fmt>
1653    : TEST_Op<"format_optional_result_" # suffix # "_op",
1654              [AttrSizedResultSegments]> {
1655  let results = (outs Optional<I64>:$optional, Variadic<I64>:$variadic);
1656  let assemblyFormat = fmt;
1657}
1658def FormatOptionalResultAOp : FormatOptionalResultOpBase<"a", [{
1659  (`:` type($optional)^ `->` type($variadic))? attr-dict
1660}]>;
1661
1662def FormatOptionalResultBOp : FormatOptionalResultOpBase<"b", [{
1663  (`:` type($optional) `->` type($variadic)^)? attr-dict
1664}]>;
1665
1666def FormatOptionalResultCOp : FormatOptionalResultOpBase<"c", [{
1667  (`:` functional-type($optional, $variadic)^)? attr-dict
1668}]>;
1669
1670def FormatTwoVariadicOperandsNoBuildableTypeOp
1671    : TEST_Op<"format_two_variadic_operands_no_buildable_type_op",
1672              [AttrSizedOperandSegments]> {
1673  let arguments = (ins Variadic<AnyType>:$a,
1674                       Variadic<AnyType>:$b);
1675  let assemblyFormat = [{
1676    `(` $a `:` type($a) `)` `->` `(` $b `:` type($b) `)`  attr-dict
1677  }];
1678}
1679
1680def FormatInferVariadicTypeFromNonVariadic
1681    : TEST_Op<"format_infer_variadic_type_from_non_variadic",
1682              [SameOperandsAndResultType]> {
1683  let arguments = (ins Variadic<AnyType>:$operands);
1684  let results = (outs AnyType:$result);
1685  let assemblyFormat = "$operands attr-dict `:` type($result)";
1686}
1687
1688def FormatOptionalUnitAttr : TEST_Op<"format_optional_unit_attribute"> {
1689  let arguments = (ins UnitAttr:$is_optional);
1690  let assemblyFormat = "(`is_optional` $is_optional^)? attr-dict";
1691}
1692
1693def FormatOptionalUnitAttrNoElide
1694    : TEST_Op<"format_optional_unit_attribute_no_elide"> {
1695  let arguments = (ins UnitAttr:$is_optional);
1696  let assemblyFormat = "($is_optional^)? attr-dict";
1697}
1698
1699def FormatOptionalEnumAttr : TEST_Op<"format_optional_enum_attr"> {
1700  let arguments = (ins OptionalAttr<SomeI64Enum>:$attr);
1701  let assemblyFormat = "($attr^)? attr-dict";
1702}
1703
1704def FormatOptionalWithElse : TEST_Op<"format_optional_else"> {
1705  let arguments = (ins UnitAttr:$isFirstBranchPresent);
1706  let assemblyFormat = "(`then` $isFirstBranchPresent^):(`else`)? attr-dict";
1707}
1708
1709//===----------------------------------------------------------------------===//
1710// Custom Directives
1711
1712def FormatCustomDirectiveOperands
1713    : TEST_Op<"format_custom_directive_operands", [AttrSizedOperandSegments]> {
1714  let arguments = (ins I64:$operand, Optional<I64>:$optOperand,
1715                       Variadic<I64>:$varOperands);
1716  let assemblyFormat = [{
1717    custom<CustomDirectiveOperands>(
1718      $operand, $optOperand, $varOperands
1719    )
1720    attr-dict
1721  }];
1722}
1723
1724def FormatCustomDirectiveOperandsAndTypes
1725    : TEST_Op<"format_custom_directive_operands_and_types",
1726              [AttrSizedOperandSegments]> {
1727  let arguments = (ins AnyType:$operand, Optional<AnyType>:$optOperand,
1728                       Variadic<AnyType>:$varOperands);
1729  let assemblyFormat = [{
1730    custom<CustomDirectiveOperandsAndTypes>(
1731      $operand, $optOperand, $varOperands,
1732      type($operand), type($optOperand), type($varOperands)
1733    )
1734    attr-dict
1735  }];
1736}
1737
1738def FormatCustomDirectiveRegions : TEST_Op<"format_custom_directive_regions"> {
1739  let regions = (region AnyRegion:$region, VariadicRegion<AnyRegion>:$regions);
1740  let assemblyFormat = [{
1741    custom<CustomDirectiveRegions>(
1742      $region, $regions
1743    )
1744    attr-dict
1745  }];
1746}
1747
1748def FormatCustomDirectiveResults
1749    : TEST_Op<"format_custom_directive_results", [AttrSizedResultSegments]> {
1750  let results = (outs AnyType:$result, Optional<AnyType>:$optResult,
1751                      Variadic<AnyType>:$varResults);
1752  let assemblyFormat = [{
1753    custom<CustomDirectiveResults>(
1754      type($result), type($optResult), type($varResults)
1755    )
1756    attr-dict
1757  }];
1758}
1759
1760def FormatCustomDirectiveResultsWithTypeRefs
1761    : TEST_Op<"format_custom_directive_results_with_type_refs",
1762              [AttrSizedResultSegments]> {
1763  let results = (outs AnyType:$result, Optional<AnyType>:$optResult,
1764                      Variadic<AnyType>:$varResults);
1765  let assemblyFormat = [{
1766    custom<CustomDirectiveResults>(
1767      type($result), type($optResult), type($varResults)
1768    )
1769    custom<CustomDirectiveWithTypeRefs>(
1770      ref(type($result)), ref(type($optResult)), ref(type($varResults))
1771    )
1772    attr-dict
1773  }];
1774}
1775
1776def FormatCustomDirectiveWithOptionalOperandRef
1777    : TEST_Op<"format_custom_directive_with_optional_operand_ref"> {
1778  let arguments = (ins Optional<I64>:$optOperand);
1779  let assemblyFormat = [{
1780    ($optOperand^)? `:`
1781    custom<CustomDirectiveOptionalOperandRef>(ref($optOperand))
1782    attr-dict
1783  }];
1784}
1785
1786def FormatCustomDirectiveSuccessors
1787    : TEST_Op<"format_custom_directive_successors", [Terminator]> {
1788  let successors = (successor AnySuccessor:$successor,
1789                              VariadicSuccessor<AnySuccessor>:$successors);
1790  let assemblyFormat = [{
1791    custom<CustomDirectiveSuccessors>(
1792      $successor, $successors
1793    )
1794    attr-dict
1795  }];
1796}
1797
1798def FormatCustomDirectiveAttributes
1799    : TEST_Op<"format_custom_directive_attributes"> {
1800  let arguments = (ins I64Attr:$attr, OptionalAttr<I64Attr>:$optAttr);
1801  let assemblyFormat = [{
1802    custom<CustomDirectiveAttributes>(
1803      $attr, $optAttr
1804    )
1805    attr-dict
1806  }];
1807}
1808
1809def FormatCustomDirectiveAttrDict
1810    : TEST_Op<"format_custom_directive_attrdict"> {
1811  let arguments = (ins I64Attr:$attr, OptionalAttr<I64Attr>:$optAttr);
1812  let assemblyFormat = [{
1813    custom<CustomDirectiveAttrDict>( attr-dict )
1814  }];
1815}
1816
1817//===----------------------------------------------------------------------===//
1818// AllTypesMatch type inference
1819
1820def FormatAllTypesMatchVarOp : TEST_Op<"format_all_types_match_var", [
1821    AllTypesMatch<["value1", "value2", "result"]>
1822  ]> {
1823  let arguments = (ins AnyType:$value1, AnyType:$value2);
1824  let results = (outs AnyType:$result);
1825  let assemblyFormat = "attr-dict $value1 `,` $value2 `:` type($value1)";
1826}
1827
1828def FormatAllTypesMatchAttrOp : TEST_Op<"format_all_types_match_attr", [
1829    AllTypesMatch<["value1", "value2", "result"]>
1830  ]> {
1831  let arguments = (ins AnyAttr:$value1, AnyType:$value2);
1832  let results = (outs AnyType:$result);
1833  let assemblyFormat = "attr-dict $value1 `,` $value2";
1834}
1835
1836//===----------------------------------------------------------------------===//
1837// TypesMatchWith type inference
1838
1839def FormatTypesMatchVarOp : TEST_Op<"format_types_match_var", [
1840    TypesMatchWith<"result type matches operand", "value", "result", "$_self">
1841  ]> {
1842  let arguments = (ins AnyType:$value);
1843  let results = (outs AnyType:$result);
1844  let assemblyFormat = "attr-dict $value `:` type($value)";
1845}
1846
1847def FormatTypesMatchVariadicOp : TEST_Op<"format_types_match_variadic", [
1848    RangedTypesMatchWith<"result type matches operand", "value", "result",
1849                         "llvm::make_range($_self.begin(), $_self.end())">
1850  ]> {
1851  let arguments = (ins Variadic<AnyType>:$value);
1852  let results = (outs Variadic<AnyType>:$result);
1853  let assemblyFormat = "attr-dict $value `:` type($value)";
1854}
1855
1856def FormatTypesMatchAttrOp : TEST_Op<"format_types_match_attr", [
1857    TypesMatchWith<"result type matches constant", "value", "result", "$_self">
1858  ]> {
1859  let arguments = (ins AnyAttr:$value);
1860  let results = (outs AnyType:$result);
1861  let assemblyFormat = "attr-dict $value";
1862}
1863
1864//===----------------------------------------------------------------------===//
1865// Test SideEffects
1866//===----------------------------------------------------------------------===//
1867
1868def SideEffectOp : TEST_Op<"side_effect_op",
1869    [DeclareOpInterfaceMethods<MemoryEffectsOpInterface>,
1870     DeclareOpInterfaceMethods<TestEffectOpInterface>]> {
1871  let results = (outs AnyType:$result);
1872}
1873
1874//===----------------------------------------------------------------------===//
1875// Test CopyOpInterface
1876//===----------------------------------------------------------------------===//
1877
1878def CopyOp : TEST_Op<"copy", [CopyOpInterface]> {
1879  let description = [{
1880    Represents a copy operation.
1881  }];
1882  let arguments = (ins Res<AnyMemRef, "", [MemRead]>:$source,
1883                   Res<AnyMemRef, "", [MemWrite]>:$target);
1884  let assemblyFormat = [{
1885    `(` $source `,` $target `)` `:` `(` type($source) `,` type($target) `)`
1886     attr-dict
1887  }];
1888  let extraClassDeclaration = [{
1889    Value getSource() { return source(); }
1890    Value getTarget() { return target(); }
1891  }];
1892}
1893
1894//===----------------------------------------------------------------------===//
1895// Test Buffer/Tensor
1896//===----------------------------------------------------------------------===//
1897
1898def RegionYieldOp : TEST_Op<"region_yield",
1899      [NoSideEffect, ReturnLike, Terminator]> {
1900  let description = [{
1901    This operation is used in a region and yields the corresponding type for
1902    that operation.
1903  }];
1904  let arguments = (ins AnyType:$result);
1905  let assemblyFormat = [{
1906    $result `:` type($result) attr-dict
1907  }];
1908  let builders = [OpBuilder<(ins),
1909    [{ build($_builder, $_state, {}); }]>
1910  ];
1911}
1912
1913class BufferBasedOpBase<string mnemonic, list<OpTrait> traits>
1914    : TEST_Op<mnemonic, traits> {
1915  let description = [{
1916    A buffer based operation, that uses memRefs as input and output.
1917  }];
1918  let arguments = (ins AnyMemRef:$input, AnyMemRef:$output);
1919}
1920
1921def BufferBasedOp : BufferBasedOpBase<"buffer_based", []>{
1922  let assemblyFormat = [{
1923    `in` `(` $input`:` type($input) `)` `out` `(` $output`:` type($output) `)`
1924    attr-dict
1925  }];
1926}
1927
1928def RegionBufferBasedOp : BufferBasedOpBase<"region_buffer_based",
1929      [SingleBlockImplicitTerminator<"RegionYieldOp">]> {
1930  let regions = (region AnyRegion:$region);
1931  let assemblyFormat = [{
1932    `in` `(` $input`:` type($input) `)` `out` `(` $output`:` type($output) `)`
1933    $region attr-dict
1934  }];
1935}
1936
1937def TensorBasedOp : TEST_Op<"tensor_based", []> {
1938  let description = [{
1939    A tensor based operation, that uses a tensor as an input and results in a
1940    tensor again.
1941  }];
1942  let arguments = (ins AnyRankedTensor:$input);
1943  let results = (outs AnyRankedTensor:$result);
1944  let assemblyFormat = [{
1945    `in` `(` $input`:` type($input) `)` `->` type($result) attr-dict
1946  }];
1947}
1948
1949//===----------------------------------------------------------------------===//
1950// Test RegionBranchOpInterface
1951//===----------------------------------------------------------------------===//
1952
1953def RegionIfYieldOp : TEST_Op<"region_if_yield",
1954      [NoSideEffect, ReturnLike, Terminator]> {
1955  let arguments = (ins Variadic<AnyType>:$results);
1956  let assemblyFormat = [{
1957    $results `:` type($results) attr-dict
1958  }];
1959}
1960
1961def RegionIfOp : TEST_Op<"region_if",
1962      [DeclareOpInterfaceMethods<RegionBranchOpInterface>,
1963       SingleBlockImplicitTerminator<"RegionIfYieldOp">,
1964       RecursiveSideEffects]> {
1965  let description =[{
1966    Represents an abstract if-then-else-join pattern. In this context, the then
1967    and else regions jump to the join region, which finally returns to its
1968    parent op.
1969    }];
1970
1971  let printer = [{ return ::print(p, *this); }];
1972  let parser = [{ return ::parseRegionIfOp(parser, result); }];
1973  let arguments = (ins Variadic<AnyType>);
1974  let results = (outs Variadic<AnyType>:$results);
1975  let regions = (region SizedRegion<1>:$thenRegion,
1976                        AnyRegion:$elseRegion,
1977                        AnyRegion:$joinRegion);
1978  let extraClassDeclaration = [{
1979    Block::BlockArgListType getThenArgs() {
1980      return getBody(0)->getArguments();
1981    }
1982    Block::BlockArgListType getElseArgs() {
1983      return getBody(1)->getArguments();
1984    }
1985    Block::BlockArgListType getJoinArgs() {
1986      return getBody(2)->getArguments();
1987    }
1988    OperandRange getSuccessorEntryOperands(unsigned index);
1989  }];
1990}
1991
1992//===----------------------------------------------------------------------===//
1993// Test TableGen generated build() methods
1994//===----------------------------------------------------------------------===//
1995
1996def TableGenConstant : TEST_Op<"tblgen_constant"> {
1997  let results = (outs AnyType);
1998}
1999
2000// No variadic args or results.
2001def TableGenBuildOp0 : TEST_Op<"tblgen_build_0"> {
2002  let arguments = (ins AnyType:$value);
2003  let results = (outs AnyType:$result);
2004}
2005
2006// Sigle variadic arg and single variadic results.
2007def TableGenBuildOp1 : TEST_Op<"tblgen_build_1"> {
2008  let arguments = (ins Variadic<AnyType>:$inputs);
2009  let results = (outs Variadic<AnyType>:$results);
2010}
2011
2012// Single variadic arg and non-variadic results.
2013def TableGenBuildOp2 : TEST_Op<"tblgen_build_2"> {
2014  let arguments = (ins Variadic<AnyType>:$inputs);
2015  let results = (outs AnyType:$result);
2016}
2017
2018// Single variadic arg and multiple variadic results.
2019def TableGenBuildOp3 : TEST_Op<"tblgen_build_3", [SameVariadicResultSize]> {
2020  let arguments = (ins Variadic<AnyType>:$inputs);
2021  let results = (outs Variadic<AnyType>:$resultA, Variadic<AnyType>:$resultB);
2022}
2023
2024// Single variadic arg, non variadic results, with SameOperandsAndResultType.
2025// Tests suppression of ambiguous build methods for operations with
2026// SameOperandsAndResultType trait.
2027def TableGenBuildOp4 : TEST_Op<"tblgen_build_4", [SameOperandsAndResultType]> {
2028  let arguments = (ins Variadic<AnyType>:$inputs);
2029  let results = (outs AnyType:$result);
2030}
2031
2032// Single variadic arg with SameOperandsAndResultType and InferTypeOpInterface.
2033// Tests suppression of ambiguous build methods for operations with
2034// SameOperandsAndResultType and InferTypeOpInterface.
2035def TableGenBuildOp5 : TEST_Op<"tblgen_build_5",
2036      [SameOperandsAndResultType, InferTypeOpInterface]> {
2037  let arguments = (ins Variadic<AnyType>:$inputs);
2038  let results = (outs AnyType:$result);
2039
2040  let extraClassDeclaration = [{
2041    static LogicalResult inferReturnTypes(MLIRContext *,
2042          Optional<Location> location, ValueRange operands,
2043          DictionaryAttr attributes, RegionRange regions,
2044          SmallVectorImpl<Type> &inferredReturnTypes) {
2045      inferredReturnTypes.assign({operands[0].getType()});
2046      return success();
2047    }
2048   }];
2049}
2050
2051//===----------------------------------------------------------------------===//
2052// Test BufferPlacement
2053//===----------------------------------------------------------------------===//
2054
2055def GetTupleElementOp: TEST_Op<"get_tuple_element"> {
2056  let description = [{
2057    Test op that returns a specified element of the tuple.
2058  }];
2059
2060  let arguments = (ins
2061    TupleOf<[AnyType]>,
2062    I32Attr:$index
2063  );
2064  let results = (outs AnyType);
2065}
2066
2067def MakeTupleOp: TEST_Op<"make_tuple"> {
2068  let description = [{
2069    Test op that creates a tuple value from a list of values.
2070  }];
2071
2072  let arguments = (ins
2073    Variadic<AnyType>:$inputs
2074  );
2075  let results = (outs TupleOf<[AnyType]>);
2076}
2077
2078//===----------------------------------------------------------------------===//
2079// Test Target DataLayout
2080//===----------------------------------------------------------------------===//
2081
2082def OpWithDataLayoutOp : TEST_Op<"op_with_data_layout",
2083                                 [HasDefaultDLTIDataLayout, DataLayoutOpInterface]> {
2084  let summary =
2085      "An op that uses DataLayout implementation from the Target dialect";
2086  let regions = (region VariadicRegion<AnyRegion>:$regions);
2087}
2088
2089def DataLayoutQueryOp : TEST_Op<"data_layout_query"> {
2090  let summary = "A token op recognized by data layout query test pass";
2091  let description = [{
2092    The data layout query pass pattern-matches this op and attaches to it an
2093    array attribute containing the result of data layout query of the result
2094    type of this op.
2095  }];
2096
2097  let results = (outs AnyType:$res);
2098}
2099
2100#endif // TEST_OPS
2101