/
FIROps.td
2965 lines (2480 loc) · 100 KB
/
FIROps.td
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
//===-- FIROps.td - FIR operation definitions --------------*- 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 FIR dialect operations
///
//===----------------------------------------------------------------------===//
#ifndef FIR_DIALECT_FIR_OPS
#define FIR_DIALECT_FIR_OPS
include "mlir/IR/SymbolInterfaces.td"
include "mlir/Interfaces/ControlFlowInterfaces.td"
include "mlir/Interfaces/LoopLikeInterface.td"
include "mlir/Interfaces/SideEffectInterfaces.td"
def fir_Dialect : Dialect {
let name = "fir";
}
// Types and predicates
def fir_Type : Type<CPred<"fir::isa_fir_or_std_type($_self)">,
"FIR dialect type">;
// Fortran intrinsic types
def fir_CharacterType : Type<CPred<"$_self.isa<fir::CharacterType>()">,
"FIR character type">;
def fir_ComplexType : Type<CPred<"$_self.isa<fir::CplxType>()">,
"FIR complex type">;
def fir_IntegerType : Type<CPred<"$_self.isa<fir::IntType>()">,
"FIR integer type">;
def fir_LogicalType : Type<CPred<"$_self.isa<fir::LogicalType>()">,
"FIR logical type">;
def fir_RealType : Type<CPred<"$_self.isa<fir::RealType>()">,
"FIR real type">;
// Generalized FIR and standard dialect types representing intrinsic types
def AnyIntegerLike : TypeConstraint<Or<[SignlessIntegerLike.predicate,
fir_IntegerType.predicate]>, "any integer">;
def AnyLogicalLike : TypeConstraint<Or<[BoolLike.predicate,
fir_LogicalType.predicate]>, "any logical">;
def AnyRealLike : TypeConstraint<Or<[FloatLike.predicate,
fir_RealType.predicate]>, "any real">;
def AnyIntegerType : Type<AnyIntegerLike.predicate, "any integer">;
// Fortran derived (user defined) type
def fir_RecordType : Type<CPred<"$_self.isa<fir::RecordType>()">,
"FIR derived type">;
// Fortran array attribute
def fir_SequenceType : Type<CPred<"$_self.isa<fir::SequenceType>()">,
"array type">;
// Composable types
def AnyCompositeLike : TypeConstraint<Or<[fir_RecordType.predicate,
fir_SequenceType.predicate, fir_ComplexType.predicate,
IsTupleTypePred]>, "any composite">;
// Reference to an entity type
def fir_ReferenceType : Type<CPred<"$_self.isa<fir::ReferenceType>()">,
"reference type">;
// Reference to an ALLOCATABLE attribute type
def fir_HeapType : Type<CPred<"$_self.isa<fir::HeapType>()">,
"allocatable type">;
// Reference to a POINTER attribute type
def fir_PointerType : Type<CPred<"$_self.isa<fir::PointerType>()">,
"pointer type">;
// Reference types
def AnyReferenceLike : TypeConstraint<Or<[fir_ReferenceType.predicate,
fir_HeapType.predicate, fir_PointerType.predicate]>, "any reference">;
// A descriptor tuple (captures a reference to an entity and other information)
def fir_BoxType : Type<CPred<"$_self.isa<fir::BoxType>()">, "box type">;
// CHARACTER type descriptor. A pair of a data reference and a LEN value.
def fir_BoxCharType : Type<CPred<"$_self.isa<fir::BoxCharType>()">,
"box character type">;
// PROCEDURE POINTER descriptor. A pair that can capture a host closure.
def fir_BoxProcType : Type<CPred<"$_self.isa<fir::BoxProcType>()">,
"box procedure type">;
def AnyBoxLike : TypeConstraint<Or<[fir_BoxType.predicate,
fir_BoxCharType.predicate, fir_BoxProcType.predicate]>, "any box">;
def AnyRefOrBox : TypeConstraint<Or<[fir_ReferenceType.predicate,
fir_HeapType.predicate, fir_PointerType.predicate, fir_BoxType.predicate]>,
"any reference or box">;
// A vector of Fortran triple notation describing a multidimensional array
def fir_DimsType : Type<CPred<"$_self.isa<fir::DimsType>()">, "dim type">;
def AnyEmboxLike : TypeConstraint<Or<[AnySignlessInteger.predicate,
Index.predicate, fir_IntegerType.predicate, fir_DimsType.predicate]>,
"any legal embox argument type">;
def AnyEmboxArg : Type<AnyEmboxLike.predicate, "embox argument type">;
// A type descriptor's type
def fir_TypeDescType : Type<CPred<"$_self.isa<fir::TypeDescType>()">,
"type desc type">;
// A field (in a RecordType) argument's type
def fir_FieldType : Type<CPred<"$_self.isa<fir::FieldType>()">, "field type">;
// A LEN parameter (in a RecordType) argument's type
def fir_LenType : Type<CPred<"$_self.isa<fir::LenType>()">,
"LEN parameter type">;
def AnyComponentLike : TypeConstraint<Or<[AnySignlessInteger.predicate,
Index.predicate, fir_IntegerType.predicate, fir_FieldType.predicate]>,
"any coordinate index">;
def AnyComponentType : Type<AnyComponentLike.predicate, "coordinate type">;
def AnyCoordinateLike : TypeConstraint<Or<[AnySignlessInteger.predicate,
Index.predicate, fir_IntegerType.predicate, fir_FieldType.predicate,
fir_LenType.predicate]>, "any coordinate index">;
def AnyCoordinateType : Type<AnyCoordinateLike.predicate, "coordinate type">;
// Base class for FIR operations.
// All operations automatically get a prefix of "fir.".
class fir_Op<string mnemonic, list<OpTrait> traits>
: Op<fir_Dialect, mnemonic, traits>;
// Base class for FIR operations that take a single argument
class fir_SimpleOp<string mnemonic, list<OpTrait> traits>
: fir_Op<mnemonic, traits> {
let assemblyFormat = [{
operands attr-dict `:` functional-type(operands, results)
}];
}
// Base builder for allocate operations
def fir_AllocateOpBuilder : OpBuilder<
"OpBuilder &builder, OperationState &result, Type inType,"
"ValueRange lenParams = {}, ValueRange sizes = {},"
"ArrayRef<NamedAttribute> attributes = {}",
[{
result.addTypes(getRefTy(inType));
result.addAttribute("in_type", TypeAttr::get(inType));
result.addOperands(sizes);
result.addAttributes(attributes);
}]>;
def fir_NamedAllocateOpBuilder : OpBuilder<
"OpBuilder &builder, OperationState &result, Type inType, StringRef name,"
"ValueRange lenParams = {}, ValueRange sizes = {},"
"ArrayRef<NamedAttribute> attributes = {}",
[{
result.addTypes(getRefTy(inType));
result.addAttribute("in_type", TypeAttr::get(inType));
result.addAttribute("name", builder.getStringAttr(name));
result.addOperands(sizes);
result.addAttributes(attributes);
}]>;
def fir_OneResultOpBuilder : OpBuilder<
"OpBuilder &, OperationState &result, Type resultType,"
"ValueRange operands, ArrayRef<NamedAttribute> attributes = {}",
[{
if (resultType)
result.addTypes(resultType);
result.addOperands(operands);
result.addAttributes(attributes);
}]>;
// Base class of FIR operations that return 1 result
class fir_OneResultOp<string mnemonic, list<OpTrait> traits = []> :
fir_Op<mnemonic, traits>, Results<(outs fir_Type:$res)> {
let builders = [fir_OneResultOpBuilder];
}
// Base class of FIR operations that have 1 argument and return 1 result
class fir_SimpleOneResultOp<string mnemonic, list<OpTrait> traits = []> :
fir_SimpleOp<mnemonic, traits> {
let builders = [fir_OneResultOpBuilder];
}
class fir_TwoBuilders<OpBuilder b1, OpBuilder b2> {
list<OpBuilder> builders = [b1, b2];
}
class fir_AllocatableBaseOp<string mnemonic, list<OpTrait> traits = []> :
fir_Op<mnemonic, traits>, Results<(outs fir_Type:$res)> {
let arguments = (ins
OptionalAttr<StrAttr>:$name,
OptionalAttr<BoolAttr>:$target
);
}
class fir_AllocatableOp<string mnemonic, list<OpTrait> traits = []> :
fir_AllocatableBaseOp<mnemonic,
!listconcat(traits, [MemoryEffects<[MemAlloc]>])>,
fir_TwoBuilders<fir_AllocateOpBuilder, fir_NamedAllocateOpBuilder>,
Arguments<(ins TypeAttr:$in_type, Variadic<AnyIntegerType>:$args)> {
let parser = [{
mlir::Type intype;
if (parser.parseType(intype))
return mlir::failure();
auto &builder = parser.getBuilder();
result.addAttribute(inType(), mlir::TypeAttr::get(intype));
llvm::SmallVector<mlir::OpAsmParser::OperandType, 8> operands;
llvm::SmallVector<mlir::Type, 8> typeVec;
bool hasOperands = false;
if (!parser.parseOptionalLParen()) {
// parse the LEN params of the derived type. (<params> : <types>)
if (parser.parseOperandList(operands,
mlir::OpAsmParser::Delimiter::None) ||
parser.parseColonTypeList(typeVec) ||
parser.parseRParen())
return mlir::failure();
auto lens = builder.getI32IntegerAttr(operands.size());
result.addAttribute(lenpName(), lens);
hasOperands = true;
}
if (!parser.parseOptionalComma()) {
// parse size to scale by, vector of n dimensions of type index
auto opSize = operands.size();
if (parser.parseOperandList(operands, mlir::OpAsmParser::Delimiter::None))
return mlir::failure();
for (auto i = opSize, end = operands.size(); i != end; ++i)
typeVec.push_back(builder.getIndexType());
hasOperands = true;
}
if (hasOperands &&
parser.resolveOperands(operands, typeVec, parser.getNameLoc(),
result.operands))
return mlir::failure();
mlir::Type restype = wrapResultType(intype);
if (!restype) {
parser.emitError(parser.getNameLoc(), "invalid allocate type: ")
<< intype;
return mlir::failure();
}
if (parser.parseOptionalAttrDict(result.attributes) ||
parser.addTypeToList(restype, result.types))
return mlir::failure();
return mlir::success();
}];
let printer = [{
p << getOperationName() << ' ' << getAttr(inType());
if (hasLenParams()) {
// print the LEN parameters to a derived type in parens
p << '(' << getLenParams() << " : " << getLenParams().getTypes() << ')';
}
// print the shape of the allocation (if any); all must be index type
for (auto sh : getShapeOperands()) {
p << ", ";
p.printOperand(sh);
}
p.printOptionalAttrDict(getAttrs(), {inType(), lenpName()});
}];
string extraAllocClassDeclaration = [{
static constexpr llvm::StringRef inType() { return "in_type"; }
static constexpr llvm::StringRef lenpName() { return "len_param_count"; }
mlir::Type getAllocatedType();
bool hasLenParams() { return bool{getAttr(lenpName())}; }
unsigned numLenParams() {
if (auto val = getAttrOfType<mlir::IntegerAttr>(lenpName()))
return val.getInt();
return 0;
}
operand_range getLenParams() {
return {operand_begin(), operand_begin() + numLenParams()};
}
unsigned numShapeOperands() {
return operand_end() - operand_begin() + numLenParams();
}
operand_range getShapeOperands() {
return {operand_begin() + numLenParams(), operand_end()};
}
static mlir::Type getRefTy(mlir::Type ty);
/// Get the input type of the allocation
mlir::Type getInType() {
return getAttrOfType<mlir::TypeAttr>(inType()).getValue();
}
}];
// Verify checks common to all allocation operations
string allocVerify = [{
llvm::SmallVector<llvm::StringRef, 8> visited;
if (verifyInType(getInType(), visited, numShapeOperands()))
return emitOpError("invalid type for allocation");
if (verifyRecordLenParams(getInType(), numLenParams()))
return emitOpError("LEN params do not correspond to type");
}];
}
//===----------------------------------------------------------------------===//
// Memory SSA operations
//===----------------------------------------------------------------------===//
def fir_AllocaOp : fir_AllocatableOp<"alloca"> {
let summary = "allocate storage for a temporary on the stack given a type";
let description = [{
This primitive operation is used to allocate an object on the stack. A
reference to the object of type `!fir.ref<T>` is returned. The returned
object has an undefined/uninitialized state. The allocation can be given
an optional name. The allocation may have a dynamic repetition count
for allocating a sequence of locations for the specified type.
```mlir
%c = ... : i64
%x = fir.alloca i32
%y = fir.alloca !fir.array<8 x i64>
%z = fir.alloca f32, %c
%i = ... : i16
%j = ... : i32
%w = fir.alloca !fir.type<PT(len1:i16, len2:i32)> (%i, %j : i16, i32)
```
Note that in the case of `%z`, a contiguous block of memory is allocated
and its size is a runtime multiple of a 32-bit REAL value.
In the case of `%w`, the arguments `%i` and `%j` are LEN parameters
(`len1`, `len2`) to the type `PT`.
Finally, the operation is undefined if the ssa-value `%c` is negative.
}];
let results = (outs fir_ReferenceType);
let verifier = allocVerify#[{
mlir::Type outType = getType();
if (!outType.isa<fir::ReferenceType>())
return emitOpError("must be a !fir.ref type");
return mlir::success();
}];
let extraClassDeclaration = extraAllocClassDeclaration#[{
static mlir::Type wrapResultType(mlir::Type intype);
}];
}
def fir_LoadOp : fir_OneResultOp<"load", [MemoryEffects<[MemRead]>]> {
let summary = "load a value from a memory reference";
let description = [{
Load a value from a memory reference into an ssa-value (virtual register).
Produces an immutable ssa-value of the referent type. A memory reference
has type `!fir.ref<T>`, `!fir.heap<T>`, or `!fir.ptr<T>`.
```mlir
%a = fir.alloca i32
%l = fir.load %a : !fir.ref<i32>
```
The ssa-value has an undefined value if the memory reference is undefined
or null.
}];
let arguments = (ins AnyReferenceLike:$memref);
let builders = [OpBuilder<
"OpBuilder &builder, OperationState &result, Value refVal",
[{
if (!refVal) {
mlir::emitError(result.location, "LoadOp has null argument");
return;
}
auto refTy = refVal.getType().cast<fir::ReferenceType>();
result.addOperands(refVal);
result.addTypes(refTy.getEleTy());
}]
>];
let parser = [{
mlir::Type type;
mlir::OpAsmParser::OperandType oper;
if (parser.parseOperand(oper) ||
parser.parseOptionalAttrDict(result.attributes) ||
parser.parseColonType(type) ||
parser.resolveOperand(oper, type, result.operands))
return mlir::failure();
mlir::Type eleTy;
if (getElementOf(eleTy, type) ||
parser.addTypeToList(eleTy, result.types))
return mlir::failure();
return mlir::success();
}];
let printer = [{
p << getOperationName() << ' ';
p.printOperand(memref());
p.printOptionalAttrDict(getAttrs(), {});
p << " : " << memref().getType();
}];
let extraClassDeclaration = [{
static mlir::ParseResult getElementOf(mlir::Type &ele, mlir::Type ref);
}];
}
def fir_StoreOp : fir_Op<"store", [MemoryEffects<[MemWrite]>]> {
let summary = "store an SSA-value to a memory location";
let description = [{
Store an ssa-value (virtual register) to a memory reference. The stored
value must be of the same type as the referent type of the memory
reference.
```mlir
%v = ... : f64
%p = ... : !fir.ptr<f64>
fir.store %v to %p : !fir.ptr<f64>
```
The above store changes the value to which the pointer is pointing and not
the pointer itself. The operation is undefined if the memory reference,
`%p`, is undefined or null.
}];
let arguments = (ins AnyType:$value, AnyReferenceLike:$memref);
let parser = [{
mlir::Type type;
mlir::OpAsmParser::OperandType oper;
mlir::OpAsmParser::OperandType store;
if (parser.parseOperand(oper) ||
parser.parseKeyword("to") ||
parser.parseOperand(store) ||
parser.parseOptionalAttrDict(result.attributes) ||
parser.parseColonType(type) ||
parser.resolveOperand(oper, elementType(type),
result.operands) ||
parser.resolveOperand(store, type, result.operands))
return mlir::failure();
return mlir::success();
}];
let printer = [{
p << getOperationName() << ' ';
p.printOperand(value());
p << " to ";
p.printOperand(memref());
p.printOptionalAttrDict(getAttrs(), {});
p << " : " << memref().getType();
}];
let verifier = [{
if (value().getType() != fir::dyn_cast_ptrEleTy(memref().getType()))
return emitOpError("store value type must match memory reference type");
return mlir::success();
}];
let extraClassDeclaration = [{
static mlir::Type elementType(mlir::Type refType);
}];
}
def fir_UndefOp : fir_OneResultOp<"undefined", [NoSideEffect]> {
let summary = "explicit undefined value of some type";
let description = [{
Constructs an ssa-value of the specified type with an undefined value.
This operation is typically created internally by the mem2reg conversion
pass. An undefined value can be of any type except `!fir.ref<T>`.
```mlir
%a = fir.undefined !fir.array<10 x !fir.type<T>>
```
The example creates an array shaped ssa value. The array is rank 1, extent
10, and each element has type `!fir.type<T>`.
}];
let results = (outs AnyType:$intype);
let assemblyFormat = "type($intype) attr-dict";
let verifier = [{
// allow `undef : ref<T>` since it is a possible from transformations
return mlir::success();
}];
}
def fir_AllocMemOp : fir_AllocatableOp<"allocmem"> {
let summary = "allocate storage on the heap for an object of a given type";
let description = [{
Creates a heap memory reference suitable for storing a value of the
given type, T. The heap refernce returned has type `!fir.heap<T>`.
The memory object is in an undefined state. `allocmem` operations must
be paired with `freemem` operations to avoid memory leaks.
```mlir
%0 = fir.allocmem !fir.array<10 x f32>
fir.freemem %0 : !fir.heap<!fir.array<10 x f32>>
```
}];
let results = (outs fir_HeapType);
let verifier = allocVerify#[{
mlir::Type outType = getType();
if (!outType.dyn_cast<fir::HeapType>())
return emitOpError("must be a !fir.heap type");
return mlir::success();
}];
let extraClassDeclaration = extraAllocClassDeclaration#[{
static mlir::Type wrapResultType(mlir::Type intype);
}];
}
def fir_FreeMemOp : fir_Op<"freemem", [MemoryEffects<[MemFree]>]> {
let summary = "free a heap object";
let description = [{
Deallocates a heap memory reference that was allocated by an `allocmem`.
The memory object that is deallocated is placed in an undefined state
after `fir.freemem`. Optimizations may treat the loading of an object
in the undefined state as undefined behavior. This includes aliasing
references, such as the result of an `fir.embox`.
```mlir
%21 = fir.allocmem !fir.type<ZT(p:i32){field:i32}>
...
fir.freemem %21 : !fir.heap<!fir.type<ZT>>
```
}];
let arguments = (ins fir_HeapType:$heapref);
let assemblyFormat = "$heapref attr-dict `:` type($heapref)";
}
//===----------------------------------------------------------------------===//
// Terminator operations
//===----------------------------------------------------------------------===//
class fir_SwitchTerminatorOp<string mnemonic, list<OpTrait> traits = []> :
fir_Op<mnemonic, !listconcat(traits, [AttrSizedOperandSegments,
DeclareOpInterfaceMethods<BranchOpInterface>, Terminator])> {
let arguments = (ins
AnyType:$selector,
Variadic<AnyType>:$compareArgs,
Variadic<AnyType>:$targetArgs
);
let results = (outs);
let successors = (successor VariadicSuccessor<AnySuccessor>:$targets);
string extraSwitchClassDeclaration = [{
using Conditions = mlir::Value;
static constexpr llvm::StringRef getCasesAttr() { return "case_tags"; }
// The number of destination conditions that may be tested
unsigned getNumConditions() {
return getAttrOfType<mlir::ArrayAttr>(getCasesAttr()).size();
}
// The selector is the value being tested to determine the destination
mlir::Value getSelector() { return selector(); }
mlir::Value getSelector(llvm::ArrayRef<mlir::Value> operands) {
return operands[0];
}
// The number of blocks that may be branched to
unsigned getNumDest() { return getOperation()->getNumSuccessors(); }
llvm::Optional<mlir::OperandRange> getCompareOperands(unsigned cond);
llvm::Optional<llvm::ArrayRef<mlir::Value>> getCompareOperands(
llvm::ArrayRef<mlir::Value> operands, unsigned cond);
llvm::Optional<llvm::ArrayRef<mlir::Value>> getSuccessorOperands(
llvm::ArrayRef<mlir::Value> operands, unsigned cond);
using BranchOpInterfaceTrait::getSuccessorOperands;
// Helper function to deal with Optional operand forms
void printSuccessorAtIndex(mlir::OpAsmPrinter &p, unsigned i) {
auto *succ = getSuccessor(i);
auto ops = getSuccessorOperands(i);
if (ops.hasValue())
p.printSuccessorAndUseList(succ, ops.getValue());
else
p.printSuccessor(succ);
}
unsigned targetOffsetSize();
}];
}
class fir_IntegralSwitchTerminatorOp<string mnemonic,
list<OpTrait> traits = []> : fir_SwitchTerminatorOp<mnemonic, traits> {
let skipDefaultBuilders = 1;
let builders = [OpBuilder<
"OpBuilder &builder, OperationState &result, Value selector,"
"ArrayRef<int64_t> compareOperands, ArrayRef<Block *> destinations,"
"ArrayRef<ValueRange> destOperands = {},"
"ArrayRef<NamedAttribute> attributes = {}",
[{
result.addOperands(selector);
llvm::SmallVector<mlir::Attribute, 8> ivalues;
for (auto iv : compareOperands)
ivalues.push_back(builder.getI64IntegerAttr(iv));
ivalues.push_back(builder.getUnitAttr());
result.addAttribute(getCasesAttr(), builder.getArrayAttr(ivalues));
const auto count = destinations.size();
for (auto d : destinations)
result.addSuccessors(d);
const auto opCount = destOperands.size();
llvm::SmallVector<int32_t, 8> argOffs;
int32_t sumArgs = 0;
for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
if (i < opCount) {
result.addOperands(destOperands[i]);
const auto argSz = destOperands[i].size();
argOffs.push_back(argSz);
sumArgs += argSz;
} else {
argOffs.push_back(0);
}
}
result.addAttribute(getOperandSegmentSizeAttr(),
builder.getI32VectorAttr({1, 0, sumArgs}));
result.addAttribute(getTargetOffsetAttr(),
builder.getI32VectorAttr(argOffs));
result.addAttributes(attributes);
}]
>];
let parser = [{
mlir::OpAsmParser::OperandType selector;
mlir::Type type;
if (parseSelector(parser, result, selector, type))
return mlir::failure();
llvm::SmallVector<mlir::Attribute, 8> ivalues;
llvm::SmallVector<mlir::Block *, 8> dests;
llvm::SmallVector<llvm::SmallVector<mlir::Value, 8>, 8> destArgs;
while (true) {
mlir::Attribute ivalue; // Integer or Unit
mlir::Block *dest;
llvm::SmallVector<mlir::Value, 8> destArg;
mlir::NamedAttrList temp;
if (parser.parseAttribute(ivalue, "i", temp) ||
parser.parseComma() ||
parser.parseSuccessorAndUseList(dest, destArg))
return mlir::failure();
ivalues.push_back(ivalue);
dests.push_back(dest);
destArgs.push_back(destArg);
if (!parser.parseOptionalRSquare())
break;
if (parser.parseComma())
return mlir::failure();
}
auto &bld = parser.getBuilder();
result.addAttribute(getCasesAttr(), bld.getArrayAttr(ivalues));
llvm::SmallVector<int32_t, 8> argOffs;
int32_t sumArgs = 0;
const auto count = dests.size();
for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
result.addSuccessors(dests[i]);
result.addOperands(destArgs[i]);
auto argSize = destArgs[i].size();
argOffs.push_back(argSize);
sumArgs += argSize;
}
result.addAttribute(getOperandSegmentSizeAttr(),
bld.getI32VectorAttr({1, 0, sumArgs}));
result.addAttribute(getTargetOffsetAttr(), bld.getI32VectorAttr(argOffs));
return mlir::success();
}];
let printer = [{
p << getOperationName() << ' ';
p.printOperand(getSelector());
p << " : " << getSelector().getType() << " [";
auto cases = getAttrOfType<mlir::ArrayAttr>(getCasesAttr()).getValue();
auto count = getNumConditions();
for (decltype(count) i = 0; i != count; ++i) {
if (i)
p << ", ";
auto &attr = cases[i];
if (auto intAttr = attr.dyn_cast_or_null<mlir::IntegerAttr>())
p << intAttr.getValue();
else
p.printAttribute(attr);
p << ", ";
printSuccessorAtIndex(p, i);
}
p << ']';
p.printOptionalAttrDict(getAttrs(), {getCasesAttr(), getCompareOffsetAttr(),
getTargetOffsetAttr(), getOperandSegmentSizeAttr()});
}];
let verifier = [{
if (!(getSelector().getType().isa<mlir::IntegerType>() ||
getSelector().getType().isa<mlir::IndexType>() ||
getSelector().getType().isa<fir::IntType>()))
return emitOpError("must be an integer");
auto cases = getAttrOfType<mlir::ArrayAttr>(getCasesAttr()).getValue();
auto count = getNumDest();
if (count == 0)
return emitOpError("must have at least one successor");
if (getNumConditions() != count)
return emitOpError("number of cases and targets don't match");
if (targetOffsetSize() != count)
return emitOpError("incorrect number of successor operand groups");
for (decltype(count) i = 0; i != count; ++i) {
auto &attr = cases[i];
if (!(attr.isa<mlir::IntegerAttr>() || attr.isa<mlir::UnitAttr>()))
return emitOpError("invalid case alternative");
}
return mlir::success();
}];
let extraClassDeclaration = extraSwitchClassDeclaration;
}
def fir_SelectOp : fir_IntegralSwitchTerminatorOp<"select"> {
let summary = "a multiway branch";
let description = [{
A multiway branch terminator with similar semantics to C's `switch`
statement. A selector value is matched against a list of constants
of the same type for a match. When a match is found, control is
transferred to the corresponding basic block. A `select` must have
at least one basic block with a corresponding `unit` match, and
that block will be selected when all other conditions fail to match.
```mlir
fir.select %arg:i32 [1, ^bb1(%0 : i32),
2, ^bb2(%2,%arg,%arg2 : i32,i32,i32),
-3, ^bb3(%arg2,%2 : i32,i32),
4, ^bb4(%1 : i32),
unit, ^bb5]
```
}];
}
def fir_SelectRankOp : fir_IntegralSwitchTerminatorOp<"select_rank"> {
let summary = "Fortran's SELECT RANK statement";
let description = [{
Similar to `select`, `select_rank` provides a way to express Fortran's
SELECT RANK construct. In this case, the rank of the selector value
is matched against constants of integer type. The structure is the
same as `select`, but `select_rank` determines the rank of the selector
variable at runtime to determine the best match.
```mlir
fir.select_rank %arg:i32 [1, ^bb1(%0 : i32),
2, ^bb2(%2,%arg,%arg2 : i32,i32,i32),
3, ^bb3(%arg2,%2 : i32,i32),
-1, ^bb4(%1 : i32),
unit, ^bb5]
```
}];
}
def fir_SelectCaseOp : fir_SwitchTerminatorOp<"select_case"> {
let summary = "Fortran's SELECT CASE statement";
let description = [{
Similar to `select`, `select_case` provides a way to express Fortran's
SELECT CASE construct. In this case, the selector value is matched
against variables (not just constants) and ranges. The structure is
the same as `select`, but `select_case` allows for the expression of
more complex match conditions.
```mlir
fir.select_case %arg : i32 [
#fir.point, %0, ^bb1(%0 : i32),
#fir.lower, %1, ^bb2(%2,%arg,%arg2,%1 : i32,i32,i32,i32),
#fir.interval, %2, %3, ^bb3(%2,%arg2 : i32,i32),
#fir.upper, %arg, ^bb4(%1 : i32),
unit, ^bb5]
```
}];
let skipDefaultBuilders = 1;
let builders = [
OpBuilder<"OpBuilder &builder, OperationState &result, Value selector,"
"ArrayRef<mlir::Attribute> compareAttrs, ArrayRef<ValueRange> cmpOperands,"
"ArrayRef<Block *> destinations, ArrayRef<ValueRange> destOperands = {},"
"ArrayRef<NamedAttribute> attributes = {}">,
OpBuilder<"OpBuilder &builder, OperationState &result, Value selector,"
"ArrayRef<mlir::Attribute> compareAttrs, ArrayRef<Value> cmpOpList,"
"ArrayRef<Block *> destinations, ArrayRef<ValueRange> destOperands = {},"
"ArrayRef<NamedAttribute> attributes = {}">];
let parser = "return parseSelectCase(parser, result);";
let printer = [{
p << getOperationName() << ' ';
p.printOperand(getSelector());
p << " : " << getSelector().getType() << " [";
auto cases = getAttrOfType<mlir::ArrayAttr>(getCasesAttr()).getValue();
auto count = getNumConditions();
for (decltype(count) i = 0; i != count; ++i) {
if (i)
p << ", ";
p << cases[i] << ", ";
if (!cases[i].isa<mlir::UnitAttr>()) {
auto caseArgs = *getCompareOperands(i);
p.printOperand(*caseArgs.begin());
p << ", ";
if (cases[i].isa<fir::ClosedIntervalAttr>()) {
p.printOperand(*(++caseArgs.begin()));
p << ", ";
}
}
printSuccessorAtIndex(p, i);
}
p << ']';
p.printOptionalAttrDict(getAttrs(), {getCasesAttr(), getCompareOffsetAttr(),
getTargetOffsetAttr(), getOperandSegmentSizeAttr()});
}];
let verifier = [{
if (!(getSelector().getType().isa<mlir::IntegerType>() ||
getSelector().getType().isa<mlir::IndexType>() ||
getSelector().getType().isa<fir::IntType>() ||
getSelector().getType().isa<fir::LogicalType>() ||
getSelector().getType().isa<fir::CharacterType>()))
return emitOpError("must be an integer, character, or logical");
auto cases = getAttrOfType<mlir::ArrayAttr>(getCasesAttr()).getValue();
auto count = getNumDest();
if (count == 0)
return emitOpError("must have at least one successor");
if (getNumConditions() != count)
return emitOpError("number of conditions and successors don't match");
if (compareOffsetSize() != count)
return emitOpError("incorrect number of compare operand groups");
if (targetOffsetSize() != count)
return emitOpError("incorrect number of successor operand groups");
for (decltype(count) i = 0; i != count; ++i) {
auto &attr = cases[i];
if (!(attr.isa<fir::PointIntervalAttr>() ||
attr.isa<fir::LowerBoundAttr>() ||
attr.isa<fir::UpperBoundAttr>() ||
attr.isa<fir::ClosedIntervalAttr>() ||
attr.isa<mlir::UnitAttr>()))
return emitOpError("incorrect select case attribute type");
}
return mlir::success();
}];
let extraClassDeclaration = extraSwitchClassDeclaration#[{
unsigned compareOffsetSize();
}];
}
def fir_SelectTypeOp : fir_SwitchTerminatorOp<"select_type"> {
let summary = "Fortran's SELECT TYPE statement";
let description = [{
Similar to `select`, `select_type` provides a way to express Fortran's
SELECT TYPE construct. In this case, the type of the selector value
is matched against a list of type descriptors. The structure is the
same as `select`, but `select_type` determines the type of the selector
variable at runtime to determine the best match.
```mlir
fir.select_type %arg : !fir.box<()> [
#fir.instance<!fir.type<type1>>, ^bb1(%0 : i32),
#fir.instance<!fir.type<type2>>, ^bb2(%2 : i32),
#fir.subsumed<!fir.type<type3>>, ^bb3(%2 : i32),
#fir.instance<!fir.type<type4>>, ^bb4(%1,%3 : i32,f32),
unit, ^bb5]
```
}];
let skipDefaultBuilders = 1;
let builders = [OpBuilder<
"OpBuilder &builder, OperationState &result, Value selector,"
"ArrayRef<mlir::Attribute> typeOperands,"
"ArrayRef<Block *> destinations, ArrayRef<ValueRange> destOperands = {},"
"ArrayRef<NamedAttribute> attributes = {}",
[{
result.addOperands(selector);
result.addAttribute(getCasesAttr(), builder.getArrayAttr(typeOperands));
const auto count = destinations.size();
for (auto d : destinations)
result.addSuccessors(d);
const auto opCount = destOperands.size();
llvm::SmallVector<int32_t, 8> argOffs;
int32_t sumArgs = 0;
for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
if (i < opCount) {
result.addOperands(destOperands[i]);
const auto argSz = destOperands[i].size();
argOffs.push_back(argSz);
sumArgs += argSz;
} else {
argOffs.push_back(0);
}
}
result.addAttribute(getOperandSegmentSizeAttr(),
builder.getI32VectorAttr({1, 0, sumArgs}));
result.addAttribute(getTargetOffsetAttr(),
builder.getI32VectorAttr(argOffs));
result.addAttributes(attributes);
}]
>];
let parser = "return parseSelectType(parser, result);";
let printer = [{
p << getOperationName() << ' ';
p.printOperand(getSelector());
p << " : " << getSelector().getType() << " [";
auto cases = getAttrOfType<mlir::ArrayAttr>(getCasesAttr()).getValue();
auto count = getNumConditions();
for (decltype(count) i = 0; i != count; ++i) {
if (i)
p << ", ";
p << cases[i] << ", ";
printSuccessorAtIndex(p, i);
}
p << ']';
p.printOptionalAttrDict(getAttrs(), {getCasesAttr(), getCompareOffsetAttr(),
getTargetOffsetAttr(), getOperandSegmentSizeAttr()});
}];
let verifier = [{
if (!(getSelector().getType().isa<fir::BoxType>()))
return emitOpError("must be a boxed type");
auto cases = getAttrOfType<mlir::ArrayAttr>(getCasesAttr()).getValue();
auto count = getNumDest();
if (count == 0)
return emitOpError("must have at least one successor");
if (getNumConditions() != count)
return emitOpError("number of conditions and successors don't match");
if (targetOffsetSize() != count)
return emitOpError("incorrect number of successor operand groups");
for (decltype(count) i = 0; i != count; ++i) {
auto &attr = cases[i];
if (!(attr.isa<fir::ExactTypeAttr>() || attr.isa<fir::SubclassAttr>() ||
attr.isa<mlir::UnitAttr>()))
return emitOpError("invalid type-case alternative");
}
return mlir::success();
}];
let extraClassDeclaration = extraSwitchClassDeclaration;
}
def fir_UnreachableOp : fir_Op<"unreachable", [Terminator]> {
let summary = "the unreachable instruction";
let description = [{
Terminates a basic block with the assertion that the end of the block
will never be reached at runtime. This instruction can be used
immediately after a call to the Fortran runtime to terminate the
program, for example. This instruction corresponds to the LLVM IR
instruction `unreachable`.
```mlir
fir.unreachable
```
}];
let parser = "return mlir::success();";
let printer = "p << getOperationName();";
}
def fir_FirEndOp : fir_Op<"end", [Terminator]> {
let summary = "the end instruction";
let description = [{
The end terminator is a special terminator used inside various FIR
operations that have regions. End is thus the custom invisible terminator
for these operations. It is implicit and need not appear in the textual
representation.
}];
}
def fir_HasValueOp : fir_Op<"has_value", [Terminator, HasParent<"GlobalOp">]> {
let summary = "terminator for GlobalOp";
let description = [{
The terminator for a GlobalOp with a body.
```mlir
global @variable : tuple<i32, f32> {