forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCIROps.td
More file actions
5343 lines (4414 loc) · 176 KB
/
CIROps.td
File metadata and controls
5343 lines (4414 loc) · 176 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===-- CIROps.td - CIR dialect definition -----------------*- tablegen -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Definition of the CIR dialect
///
//===----------------------------------------------------------------------===//
#ifndef CLANG_CIR_DIALECT_IR_CIROPS_TD
#define CLANG_CIR_DIALECT_IR_CIROPS_TD
include "clang/CIR/Dialect/IR/CIRDialect.td"
include "clang/CIR/Dialect/IR/CIRTypes.td"
include "clang/CIR/Dialect/IR/CIRAttrs.td"
include "clang/CIR/Dialect/IR/CIRAttrConstraints.td"
include "clang/CIR/Interfaces/CIROpInterfaces.td"
include "clang/CIR/Interfaces/CIRLoopOpInterface.td"
include "mlir/IR/BuiltinAttributeInterfaces.td"
include "mlir/IR/EnumAttr.td"
include "mlir/IR/SymbolInterfaces.td"
include "mlir/IR/CommonAttrConstraints.td"
include "mlir/Interfaces/ControlFlowInterfaces.td"
include "mlir/Interfaces/FunctionInterfaces.td"
include "mlir/Interfaces/InferTypeOpInterface.td"
include "mlir/Interfaces/LoopLikeInterface.td"
include "mlir/Interfaces/MemorySlotInterfaces.td"
include "mlir/Interfaces/SideEffectInterfaces.td"
//===----------------------------------------------------------------------===//
// CIR Ops
//===----------------------------------------------------------------------===//
// LLVMLoweringInfo is used by cir-tablegen to generate LLVM lowering logic
// automatically for CIR operations. The `llvmOp` field gives the name of the
// LLVM IR dialect operation that the CIR operation will be lowered to. The
// input arguments of the CIR operation will be passed in the same order to the
// lowered LLVM IR operation.
//
// Example:
//
// For the following CIR operation definition:
//
// def FooOp : CIR_Op<"foo"> {
// // ...
// let arguments = (ins CIR_AnyType:$arg1, CIR_AnyType:$arg2);
// let llvmOp = "BarOp";
// }
//
// cir-tablegen will generate LLVM lowering code for the FooOp similar to the
// following:
//
// class CIRFooOpLowering
// : public mlir::OpConversionPattern<cir::FooOp> {
// public:
// using OpConversionPattern<cir::FooOp>::OpConversionPattern;
//
// mlir::LogicalResult matchAndRewrite(
// cir::FooOp op,
// OpAdaptor adaptor,
// mlir::ConversionPatternRewriter &rewriter) const override {
// rewriter.replaceOpWithNewOp<mlir::LLVM::BarOp>(
// op, adaptor.getOperands()[0], adaptor.getOperands()[1]);
// return mlir::success();
// }
// }
//
// If you want fully customized LLVM IR lowering logic, simply exclude the
// `llvmOp` field from your CIR operation definition.
class LLVMLoweringInfo {
string llvmOp = "";
}
class CIR_Op<string mnemonic, list<Trait> traits = []> :
Op<CIR_Dialect, mnemonic, traits>, LLVMLoweringInfo {
// Should we generate an LLVM lowering pattern for this op?
bit hasLLVMLowering = true;
// Is the LLVM lowering pattern for this operation recursive?
bit isLLVMLoweringRecursive = false;
// Extra class declarations to be included in the generated LLVM lowering
// pattern.
code extraLLVMLoweringPatternDecl = "";
}
//===----------------------------------------------------------------------===//
// CIR Operation Traits
//===----------------------------------------------------------------------===//
class HasAtMostOneOfAttrsPred<list<string> names> :
CPred<!foldl("0", names, acc, name, acc # " + (" # name # " ? 1 : 0)")
# " <= 1">;
class HasAtMostOneOfAttrs<list<string> names> : PredOpTrait<
"has only one of the optional attributes: " # !interleave(names, ", "),
HasAtMostOneOfAttrsPred<!foreach(name, names, "$" # name)>
>;
//===----------------------------------------------------------------------===//
// CastOp
//===----------------------------------------------------------------------===//
def CIR_CastKind : CIR_I32EnumAttr<"CastKind", "cast kind", [
I32EnumAttrCase<"bitcast", 1>,
// CK_LValueBitCast
// CK_LValueToRValueBitCast
// CK_LValueToRValue
// CK_NoOp
// CK_BaseToDerived
// CK_DerivedToBase
// CK_UncheckedDerivedToBase
// CK_Dynamic
// CK_ToUnion
I32EnumAttrCase<"array_to_ptrdecay", 11>,
// CK_FunctionToPointerDecay
// CK_NullToPointer
// CK_NullToMemberPointer
// CK_BaseToDerivedMemberPointer
// CK_DerivedToBaseMemberPointer
I32EnumAttrCase<"member_ptr_to_bool", 17>,
// CK_ReinterpretMemberPointer
// CK_UserDefinedConversion
// CK_ConstructorConversion
I32EnumAttrCase<"int_to_ptr", 21>,
I32EnumAttrCase<"ptr_to_int", 22>,
I32EnumAttrCase<"ptr_to_bool", 23>,
// CK_ToVoid
// CK_MatrixCast
// CK_VectorSplat
I32EnumAttrCase<"integral", 27>,
I32EnumAttrCase<"int_to_bool", 28>,
I32EnumAttrCase<"int_to_float", 29>,
// CK_FloatingToFixedPoint
// CK_FixedPointToFloating
// CK_FixedPointCast
// CK_FixedPointToIntegral
// CK_IntegralToFixedPoint
// CK_FixedPointToBoolean
I32EnumAttrCase<"float_to_int", 36>,
I32EnumAttrCase<"float_to_bool", 37>,
I32EnumAttrCase<"bool_to_int", 38>,
I32EnumAttrCase<"floating", 39>,
// CK_CPointerToObjCPointerCast
// CK_BlockPointerToObjCPointerCast
// CK_AnyPointerToBlockPointerCast
// CK_ObjCObjectLValueCast
I32EnumAttrCase<"float_to_complex", 44>,
I32EnumAttrCase<"float_complex_to_real", 45>,
I32EnumAttrCase<"float_complex_to_bool", 46>,
I32EnumAttrCase<"float_complex", 47>,
I32EnumAttrCase<"float_complex_to_int_complex", 48>,
I32EnumAttrCase<"int_to_complex", 49>,
I32EnumAttrCase<"int_complex_to_real", 50>,
I32EnumAttrCase<"int_complex_to_bool", 51>,
I32EnumAttrCase<"int_complex", 52>,
I32EnumAttrCase<"int_complex_to_float_complex", 53>,
// CK_ARCProduceObject
// CK_ARCConsumeObject
// CK_ARCReclaimReturnedObject
// CK_ARCExtendBlockObject
// CK_AtomicToNonAtomic
// CK_NonAtomicToAtomic
// CK_CopyAndAutoreleaseBlockObject
// CK_BuiltinFnToFnPtr
// CK_ZeroToOCLOpaqueType
I32EnumAttrCase<"address_space", 63>,
// CK_IntToOCLSampler
// CK_HLSLVectorTruncation
// CK_HLSLArrayRValue
// CK_HLSLElementwiseCast
// CK_HLSLAggregateSplatCast
// Enums below are specific to CIR and don't have a correspondence to classic
// codegen:
I32EnumAttrCase<"bool_to_float", 1000>,
]>;
def CIR_CastOp : CIR_Op<"cast", [
Pure, DeclareOpInterfaceMethods<PromotableOpInterface>
]> {
// FIXME: not all conversions are free of side effects.
let summary = "Conversion between values of different types";
let description = [{
Apply the usual C/C++ conversion rules between values. This operation models
a subset of conversions as defined in Clang's `OperationKinds.def`
(`llvm-project/clang/include/clang/AST/OperationKinds.def`).
Note: not all conversions are implemented using `cir.cast`. For instance,
lvalue-to-rvalue conversion is modeled as a `cir.load` instead. Currently
supported kinds:
- `bitcast`
- `array_to_ptrdecay`
- `member_ptr_to_bool
- `int_to_ptr`
- `ptr_to_int`
- `ptr_to_bool`
- `integral`
- `int_to_bool`
- `int_to_float`
- `float_to_int`
- `float_to_bool`
- `bool_to_int`
- `floating`
- `float_complex`
- `int_complex_to_real`
- `int_complex_to_bool`
- `int_complex`
- `int_complex_to_float_complex`
- `address_space`
CIR also supports some additional conversions that are not part of the classic
Clang codegen:
- `bool_to_float`
Example:
```mlir
%4 = cir.cast int_to_bool %3 : i32 -> !cir.bool
...
%x = cir.cast array_to_ptrdecay %0
: !cir.ptr<!cir.array<i32 x 10>> -> !cir.ptr<i32>
```
}];
let arguments = (ins CIR_CastKind:$kind, CIR_AnyType:$src);
let results = (outs CIR_AnyType:$result);
let assemblyFormat = [{
$kind $src `:` type($src) `->` type($result) attr-dict
}];
// The input and output types should match the cast kind.
let hasVerifier = 1;
let hasFolder = 1;
let extraLLVMLoweringPatternDecl = [{
mlir::Type convertTy(mlir::Type ty) const;
}];
}
//===----------------------------------------------------------------------===//
// DynamicCastOp
//===----------------------------------------------------------------------===//
def CIR_DynamicCastKind : CIR_I32EnumAttr<
"DynamicCastKind", "dynamic cast kind", [
I32EnumAttrCase<"Ptr", 0, "ptr">,
I32EnumAttrCase<"Ref", 1, "ref">
]>;
def CIR_DynamicCastOp : CIR_Op<"dyn_cast"> {
let summary = "Perform dynamic cast on record pointers";
let description = [{
The `cir.dyn_cast` operation models part of the semantics of the
`dynamic_cast` operator in C++. It can be used to perform 3 kinds of casts
on record pointers:
- Down-cast, which casts a base class pointer to a derived class pointer;
- Side-cast, which casts a class pointer to a sibling class pointer;
- Cast-to-complete, which casts a class pointer to a void pointer.
The input of the operation must be a record pointer. The result of the
operation is either a record pointer or a void pointer.
The parameter `kind` specifies the semantics of this operation. If its value
is `ptr`, then the operation models dynamic casts on pointers. Otherwise, if
its value is `ref`, the operation models dynamic casts on references.
Specifically:
- When the input pointer is a null pointer value:
- If `kind` is `ref`, the operation will invoke undefined behavior. A
sanitizer check will be emitted if sanitizer is on.
- Otherwise, the operation will return a null pointer value as its result.
- When the runtime type check fails:
- If `kind` is `ref`, the operation will throw a `bad_cast` exception.
- Otherwise, the operation will return a null pointer value as its result.
The `info` argument gives detailed information about the requested dynamic
cast operation. It is an optional `#cir.dyn_cast_info` attribute that is
only present when the operation models a down-cast or a side-cast.
The `relative_layout` argument specifies whether the Itanium C++ ABI vtable
uses relative layout. It is only meaningful when the operation models a
cast-to-complete operation.
Examples:
```mlir
%0 = cir.dyn_cast ptr %p : !cir.ptr<!rec_Base> -> !cir.ptr<!rec_Derived>
%1 = cir.dyn_cast ptr relative_layout %p : !cir.ptr<!rec_Base>
-> !cir.ptr<!rec_Derived>
%2 = cir.dyn_cast ref %r : !cir.ptr<!rec_Base> -> !cir.ptr<!rec_Derived>
#cir.dyn_cast_info<
srcRtti = #cir.global_view<@_ZTI4Base> : !cir.ptr<!u8i>,
destRtti = #cir.global_view<@_ZTI7Derived> : !cir.ptr<!u8i>,
runtimeFunc = @__dynamic_cast,
badCastFunc = @__cxa_bad_cast,
offsetHint = #cir.int<0> : !s64i
>
```
}];
let arguments = (ins
CIR_DynamicCastKind:$kind,
CIR_PtrToRecordType:$src,
OptionalAttr<CIR_DynamicCastInfoAttr>:$info,
UnitAttr:$relative_layout
);
let results = (outs
CIR_PtrToAnyOf<[CIR_VoidType, CIR_RecordType]>:$result
);
let assemblyFormat = [{
$kind (`relative_layout` $relative_layout^)? $src
`:` qualified(type($src)) `->` qualified(type($result))
(qualified($info)^)? attr-dict
}];
let extraClassDeclaration = [{
/// Determine whether this operation models reference casting in C++.
bool isRefCast() {
return getKind() == ::cir::DynamicCastKind::Ref;
}
/// Determine whether this operation represents a dynamic cast to a void
/// pointer.
bool isCastToVoid() {
return getType().isVoidPtr();
}
}];
let hasLLVMLowering = false;
}
//===----------------------------------------------------------------------===//
// PtrStrideOp
//===----------------------------------------------------------------------===//
def CIR_PtrStrideOp : CIR_Op<"ptr_stride", [
Pure, AllTypesMatch<["base", "result"]>
]> {
let summary = "Pointer access with stride";
let description = [{
The `cir.ptr_stride` operation computes a new pointer from a base pointer
and an integer stride, similar to a single-index `getelementptr` in LLVM IR.
It moves the pointer by `stride * sizeof(element_type)` bytes.
```mlir
%3 = cir.const 0 : i32
%3 = cir.ptr_stride %1, %2 : (!cir.ptr<i32>, i32) -> !cir.ptr<i32>
```
}];
let arguments = (ins
CIR_PointerType:$base,
CIR_AnyFundamentalIntType:$stride
);
let results = (outs CIR_PointerType:$result);
let assemblyFormat = [{
$base`,` $stride `:` functional-type(operands, results) attr-dict
}];
let extraClassDeclaration = [{
// Get type pointed by the base pointer.
mlir::Type getElementType() {
return getBase().getType().getPointee();
}
}];
}
//===----------------------------------------------------------------------===//
// ConstantOp
//===----------------------------------------------------------------------===//
def CIR_ConstantOp : CIR_Op<"const", [
ConstantLike, Pure, AllTypesMatch<["value", "res"]>
]> {
let summary = "Create a CIR constant from a literal attribute";
let description = [{
The `cir.const` operation turns a literal into an SSA value. The data is
attached to the operation as an attribute.
```mlir
%0 = cir.const #cir.int<4> : !u32i
%1 = cir.const #cir.fp<1.500000e+00> : !cir.float
%2 = cir.const #cir.ptr<null> : !cir.ptr<!void>
```
}];
let arguments = (ins TypedAttrInterface:$value);
let results = (outs CIR_AnyType:$res);
let assemblyFormat = "$value attr-dict";
let hasVerifier = 1;
let extraClassDeclaration = [{
bool isNullPtr() {
if (const auto ptrAttr = mlir::dyn_cast<cir::ConstPtrAttr>(getValue()))
return ptrAttr.isNullValue();
return false;
}
template <typename T>
T getValueAttr() { return mlir::dyn_cast<T>(getValue()); }
llvm::APInt getIntValue() {
if (const auto intAttr = getValueAttr<cir::IntAttr>())
return intAttr.getValue();
llvm_unreachable("Expected an IntAttr in ConstantOp");
}
bool getBoolValue() {
if (const auto boolAttr = getValueAttr<cir::BoolAttr>())
return boolAttr.getValue();
llvm_unreachable("Expected a BoolAttr in ConstantOp");
}
}];
let hasFolder = 1;
let isLLVMLoweringRecursive = true;
}
//===----------------------------------------------------------------------===//
// C/C++ memory order definitions
//===----------------------------------------------------------------------===//
def CIR_MemOrder : CIR_I32EnumAttr<
"MemOrder", "Memory order according to C++11 memory model", [
I32EnumAttrCase<"Relaxed", 0, "relaxed">,
I32EnumAttrCase<"Consume", 1, "consume">,
I32EnumAttrCase<"Acquire", 2, "acquire">,
I32EnumAttrCase<"Release", 3, "release">,
I32EnumAttrCase<"AcquireRelease", 4, "acq_rel">,
I32EnumAttrCase<"SequentiallyConsistent", 5, "seq_cst">
]>;
//===----------------------------------------------------------------------===//
// AllocaOp
//===----------------------------------------------------------------------===//
class CIR_AllocaTypesMatchWith<
string summary, string lhsArg, string rhsArg, string transform,
string comparator = "std::equal_to<>()"
> : PredOpTrait<summary, CPred<comparator # "(" #
!subst("$_self", "$" # lhsArg # ".getType()", transform) #
", $" # rhsArg # ")">
> {
string lhs = lhsArg;
string rhs = rhsArg;
string transformer = transform;
}
def CIR_AllocaOp : CIR_Op<"alloca", [
CIR_AllocaTypesMatchWith<"'allocaType' matches pointee type of 'addr'",
"addr", "allocaType", "mlir::cast<cir::PointerType>($_self).getPointee()">,
DeclareOpInterfaceMethods<PromotableAllocationOpInterface>
]> {
let summary = "Defines a scope-local variable";
let description = [{
The `cir.alloca` operation defines a scope-local variable.
The presence of the `const` attribute indicates that the local variable is
declared with C/C++ `const` keyword.
The `dynAllocSize` specifies the size to dynamically allocate on the stack
and ignores the allocation size based on the original type. This is useful
when handling VLAs or the `alloca` builtin and is omitted when declaring
regular local variables.
The result type is a pointer to the input's type.
Example:
```mlir
// int count;
%0 = cir.alloca i32, !cir.ptr<i32>, ["count"] {alignment = 4 : i64}
// int *ptr;
%1 = cir.alloca !cir.ptr<i32>, !cir.ptr<!cir.ptr<i32>>, ["ptr"] {alignment = 8 : i64}
...
```
}];
let arguments = (ins
Optional<CIR_AnyFundamentalIntType>:$dynAllocSize,
TypeAttr:$allocaType,
StrAttr:$name,
UnitAttr:$init,
UnitAttr:$constant,
ConfinedAttr<OptionalAttr<I64Attr>, [IntMinValue<0>]>:$alignment,
OptionalAttr<ArrayAttr>:$annotations
);
let results = (outs Res<CIR_PointerType, "",
[MemAlloc<AutomaticAllocationScopeResource>]>:$addr);
let skipDefaultBuilders = 1;
let builders = [
OpBuilder<(ins "mlir::Type":$addr,
"mlir::Type":$allocaType,
"llvm::StringRef":$name,
"mlir::IntegerAttr":$alignment)>,
OpBuilder<(ins "mlir::Type":$addr,
"mlir::Type":$allocaType,
"llvm::StringRef":$name,
"mlir::IntegerAttr":$alignment,
"mlir::Value":$dynAllocSize),
[{
if (dynAllocSize)
$_state.addOperands(dynAllocSize);
build($_builder, $_state, addr, allocaType, name, alignment);
}]>
];
let extraClassDeclaration = [{
// Whether the alloca input type is a pointer.
bool isPointerType() { return ::mlir::isa<::cir::PointerType>(getAllocaType()); }
bool isDynamic() { return (bool)getDynAllocSize(); }
}];
let assemblyFormat = [{
$allocaType `,` qualified(type($addr)) `,`
($dynAllocSize^ `:` type($dynAllocSize) `,`)?
`[` $name
(`,` `init` $init^)?
(`,` `const` $constant^)?
`]`
($annotations^)? attr-dict
}];
}
//===----------------------------------------------------------------------===//
// LoadOp
//===----------------------------------------------------------------------===//
def CIR_LoadOp : CIR_Op<"load", [
TypesMatchWith<"type of 'result' matches pointee type of 'addr'",
"addr", "result", "mlir::cast<cir::PointerType>($_self).getPointee()">,
DeclareOpInterfaceMethods<PromotableMemOpInterface>
]> {
let summary = "Load value from memory adddress";
let description = [{
`cir.load` reads a value (lvalue to rvalue conversion) given an address
backed up by a `cir.ptr` type. A unit attribute `deref` can be used to
mark the resulting value as used by another operation to dereference
a pointer. A unit attribute `volatile` can be used to indicate a volatile
loading. Load can be marked atomic by using `atomic(<mem_order>)`.
`alignment` can be used to specify an alignment that's different from the
default, which is computed from `result`'s type ABI data layout.
Example:
```mlir
// Read from local variable, address in %0.
%1 = cir.load %0 : !cir.ptr<i32>, i32
// Load address from memory at address %0. %3 is used by at least one
// operation that dereferences a pointer.
%3 = cir.load deref %0 : !cir.ptr<!cir.ptr<i32>>
// Perform a volatile load from address in %0.
%4 = cir.load volatile %0 : !cir.ptr<i32>, i32
// Others
%x = cir.load align(16) atomic(seq_cst) %0 : !cir.ptr<i32>, i32
```
}];
let arguments = (ins Arg<CIR_PointerType, "the address to load from",
[MemRead]>:$addr,
UnitAttr:$isDeref,
UnitAttr:$is_volatile,
OptionalAttr<I64Attr>:$alignment,
OptionalAttr<CIR_MemOrder>:$mem_order);
let results = (outs CIR_AnyType:$result);
let assemblyFormat = [{
(`deref` $isDeref^)?
(`volatile` $is_volatile^)?
(`align` `(` $alignment^ `)`)?
(`atomic` `(` $mem_order^ `)`)?
$addr `:` qualified(type($addr)) `,` type($result) attr-dict
}];
// FIXME: add verifier.
}
//===----------------------------------------------------------------------===//
// StoreOp
//===----------------------------------------------------------------------===//
def CIR_StoreOp : CIR_Op<"store", [
TypesMatchWith<"type of 'value' matches pointee type of 'addr'",
"addr", "value", "mlir::cast<cir::PointerType>($_self).getPointee()">,
DeclareOpInterfaceMethods<PromotableMemOpInterface>
]> {
let summary = "Store value to memory address";
let description = [{
`cir.store` stores a value (first operand) to the memory address specified
in the second operand. A unit attribute `volatile` can be used to indicate
a volatile store. Store's can be marked atomic by using
`atomic(<mem_order>)`.
`alignment` can be used to specify an alignment that's different from the
default, which is computed from `result`'s type ABI data layout.
Example:
```mlir
// Store a function argument to local storage, address in %0.
cir.store %arg0, %0 : i32, !cir.ptr<i32>
// Perform a volatile store into memory location at the address in %0.
cir.store volatile %arg0, %0 : i32, !cir.ptr<i32>
// Others
cir.store align(16) atomic(seq_cst) %x, %addr : i32, !cir.ptr<i32>
```
}];
let arguments = (ins CIR_AnyType:$value,
Arg<CIR_PointerType, "the address to store the value",
[MemWrite]>:$addr,
UnitAttr:$is_volatile,
OptionalAttr<I64Attr>:$alignment,
OptionalAttr<CIR_MemOrder>:$mem_order);
let assemblyFormat = [{
(`volatile` $is_volatile^)?
(`align` `(` $alignment^ `)`)?
(`atomic` `(` $mem_order^ `)`)?
$value `,` $addr attr-dict `:` type($value) `,` qualified(type($addr))
}];
// FIXME: add verifier.
}
//===----------------------------------------------------------------------===//
// ReturnOp
//===----------------------------------------------------------------------===//
defvar CIR_ReturnableScopes = [
"FuncOp", "ScopeOp", "IfOp", "SwitchOp", "CaseOp",
"DoWhileOp", "WhileOp", "ForOp", "TryOp"
];
def CIR_ReturnOp : CIR_Op<"return", [
ParentOneOf<CIR_ReturnableScopes>, Terminator
]> {
let summary = "Return from function";
let description = [{
The "return" operation represents a return operation within a function.
The operation takes an optional operand and produces no results.
The operand type must match the signature of the function that contains
the operation.
```mlir
func @foo() -> i32 {
...
cir.return %0 : i32
}
```
}];
// The return operation takes an optional input operand to return. This
// value must match the return type of the enclosing function.
let arguments = (ins Variadic<CIR_AnyType>:$input);
// The return operation only emits the input in the format if it is present.
let assemblyFormat = "($input^ `:` type($input))? attr-dict ";
// Allow building a ReturnOp with no return operand.
let builders = [
OpBuilder<(ins), [{ build($_builder, $_state, {}); }]>
];
// Provide extra utility definitions on the c++ operation class definition.
let extraClassDeclaration = [{
bool hasOperand() { return getNumOperands() != 0; }
}];
let hasVerifier = 1;
}
//===----------------------------------------------------------------------===//
// IfOp
//===----------------------------------------------------------------------===//
def CIR_IfOp : CIR_Op<"if", [
DeclareOpInterfaceMethods<RegionBranchOpInterface>,
RecursivelySpeculatable, AutomaticAllocationScope, NoRegionArguments
]> {
let summary = "the if-then-else operation";
let description = [{
The `cir.if` operation represents an if-then-else construct for
conditionally executing two regions of code. The operand is a `cir.bool`
type.
Examples:
```mlir
cir.if %cond {
...
} else {
...
}
cir.if %cond {
...
}
cir.if %cond {
...
cir.br ^a
^a:
cir.yield
}
```
`cir.if` defines no values and the 'else' can be omitted. The if/else
regions must be terminated. If the region has only one block, the terminator
can be left out, and `cir.yield` terminator will be inserted implictly.
Otherwise, the region must be explicitly terminated.
}];
let arguments = (ins CIR_BoolType:$condition);
let regions = (region AnyRegion:$thenRegion, AnyRegion:$elseRegion);
let hasCustomAssemblyFormat=1;
let skipDefaultBuilders=1;
let builders = [
OpBuilder<(ins "mlir::Value":$cond, "bool":$withElseRegion,
CArg<"BuilderCallbackRef", "buildTerminatedBody">:$thenBuilder,
CArg<"BuilderCallbackRef", "nullptr">:$elseBuilder)>
];
let hasLLVMLowering = false;
}
//===----------------------------------------------------------------------===//
// ConditionOp
//===----------------------------------------------------------------------===//
def CIR_ConditionOp : CIR_Op<"condition", [
Terminator,
DeclareOpInterfaceMethods<RegionBranchTerminatorOpInterface, [
"getSuccessorRegions"
]>
]> {
let summary = "Loop continuation condition.";
let description = [{
The `cir.condition` terminates conditional regions. It takes a single
`cir.bool` operand and, depending on its value, may branch to different
regions:
- When in the `cond` region of a loop, it continues the loop
if true, or exits it if false.
- When in the `ready` region of a `cir.await`, it branches to the `resume`
region when true, and to the `suspend` region when false.
Example:
```mlir
cir.for cond {
cir.condition(%val) // Branches to `step` region or exits.
} body {
cir.yield
} step {
cir.yield
}
cir.await(user, ready : {
cir.condition(%arg0) // Branches to `resume` or `suspend` region.
}, suspend : {
[...]
}, resume : {
[...]
},)
```
}];
let arguments = (ins CIR_BoolType:$condition);
let assemblyFormat = " `(` $condition `)` attr-dict ";
let hasVerifier = 1;
let hasLLVMLowering = false;
}
//===----------------------------------------------------------------------===//
// YieldOp
//===----------------------------------------------------------------------===//
defvar CIR_YieldableScopes = [
"ArrayCtor", "ArrayDtor", "AwaitOp", "CaseOp", "DoWhileOp", "ForOp",
"GlobalOp", "IfOp", "ScopeOp", "SwitchOp", "TernaryOp", "WhileOp", "TryOp"
];
def CIR_YieldOp : CIR_Op<"yield", [
ReturnLike, Terminator, ParentOneOf<CIR_YieldableScopes>
]> {
let summary = "Represents the default branching behaviour of a region";
let description = [{
The `cir.yield` operation terminates regions on different CIR operations,
and it is used to represent the default branching behaviour of a region.
Said branching behaviour is determinted by the parent operation. For
example, a yield in a `switch-case` region implies a fallthrough, while
a yield in a `cir.if` region implies a branch to the exit block, and so
on.
In some cases, it might yield an SSA value and the semantics of how the
values are yielded is defined by the parent operation. For example, a
`cir.ternary` operation yields a value from one of its regions.
As a general rule, `cir.yield` must be explicitly used whenever a region has
more than one block and no terminator, or within `cir.switch` regions not
`cir.return` terminated.
Examples:
```mlir
cir.if %4 {
...
cir.yield
}
cir.switch (%5) [
case (equal, 3) {
...
cir.yield
}, ...
]
cir.scope {
...
cir.yield
}
%x = cir.scope {
...
cir.yield %val
}
%y = cir.ternary {
...
cir.yield %val : i32
} : i32
```
}];
let arguments = (ins Variadic<CIR_AnyType>:$args);
let assemblyFormat = "($args^ `:` type($args))? attr-dict";
let builders = [
OpBuilder<(ins), [{ /* nothing to do */ }]>,
];
let hasLLVMLowering = false;
}
//===----------------------------------------------------------------------===//
// BreakOp
//===----------------------------------------------------------------------===//
def CIR_BreakOp : CIR_Op<"break", [Terminator]> {
let summary = "C/C++ `break` statement equivalent";
let description = [{
The `cir.break` operation is used to cease the execution of the current loop
or switch operation and transfer control to the parent operation. It is only
allowed within a breakable operations (loops and switches).
}];
let assemblyFormat = "attr-dict";
let hasVerifier = 1;
let hasLLVMLowering = false;
}
//===----------------------------------------------------------------------===//
// ContinueOp
//===----------------------------------------------------------------------===//
def CIR_ContinueOp : CIR_Op<"continue", [Terminator]> {
let summary = "C/C++ `continue` statement equivalent";
let description = [{
The `cir.continue` operation is used to end execution of the current
iteration of a loop and resume execution beginning at the next iteration.
It is only allowed within loop regions.
}];
let assemblyFormat = "attr-dict";
let hasVerifier = 1;
let hasLLVMLowering = false;
}
//===----------------------------------------------------------------------===//
// ScopeOp
//===----------------------------------------------------------------------===//
def CIR_ScopeOp : CIR_Op<"scope", [
DeclareOpInterfaceMethods<RegionBranchOpInterface>,
RecursivelySpeculatable, AutomaticAllocationScope, NoRegionArguments
]> {
let summary = "Represents a C/C++ scope";
let description = [{
`cir.scope` contains one region and defines a strict "scope" for all new
values produced within its blocks.
The region can contain an arbitrary number of blocks but usually defaults
to one and can optionally return a value (useful for representing values
coming out of C++ full-expressions) via `cir.yield`:
```mlir
%rvalue = cir.scope {
...
cir.yield %value
}
```
The blocks can be terminated by `cir.yield`, `cir.return` or `cir.throw`.
If `cir.scope` yields no value, the `cir.yield` can be left out, and
will be inserted implicitly.
}];
let results = (outs Optional<CIR_AnyType>:$results);
let regions = (region AnyRegion:$scopeRegion);
let hasVerifier = 1;
let skipDefaultBuilders = 1;
let assemblyFormat = [{
custom<OmittedTerminatorRegion>($scopeRegion) (`:` type($results)^)? attr-dict
}];
let extraClassDeclaration = [{
/// Determine whether the scope is empty, meaning it contains a single block
/// terminated by a cir.yield.
bool isEmpty() {
auto &entry = getRegion().front();
return getRegion().hasOneBlock() &&
llvm::isa<YieldOp>(entry.front());
}
}];
let builders = [
// Scopes for yielding values.
OpBuilder<(ins
"llvm::function_ref<void(mlir::OpBuilder &, mlir::Type &, mlir::Location)>":$scopeBuilder)>,
// Scopes without yielding values.
OpBuilder<(ins "llvm::function_ref<void(mlir::OpBuilder &, mlir::Location)>":$scopeBuilder)>
];
let hasLLVMLowering = false;
}
//===----------------------------------------------------------------------===//
// SwitchOp
//===----------------------------------------------------------------------===//
def CIR_CaseOpKind : CIR_I32EnumAttr<"CaseOpKind", "case kind", [
I32EnumAttrCase<"Default", 0, "default">,
I32EnumAttrCase<"Equal", 1, "equal">,
I32EnumAttrCase<"Anyof", 2, "anyof">,
I32EnumAttrCase<"Range", 3, "range">
]>;
def CIR_CaseOp : CIR_Op<"case", [
DeclareOpInterfaceMethods<RegionBranchOpInterface>,
RecursivelySpeculatable, AutomaticAllocationScope
]> {
let summary = "Case operation";
let description = [{
The `cir.case` operation represents a case within a C/C++ switch.
The `cir.case` operation must be in a `cir.switch` operation directly
or indirectly.
The `cir.case` have 4 kinds:
- `equal, <constant>`: equality of the second case operand against the
condition.
- `anyof, [constant-list]`: equals to any of the values in a subsequent
following list.
- `range, [lower-bound, upper-bound]`: the condition is within the closed
interval.
- `default`: any other value.
Each case region must be explicitly terminated.
}];
let arguments = (ins ArrayAttr:$value, CIR_CaseOpKind:$kind);
let regions = (region AnyRegion:$caseRegion);
let assemblyFormat = "`(` $kind `,` $value `)` $caseRegion attr-dict";
let skipDefaultBuilders = 1;
let builders = [