/
FIROps.td
2853 lines (2281 loc) · 97.6 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 FORTRAN_DIALECT_FIR_OPS
#define FORTRAN_DIALECT_FIR_OPS
include "flang/Optimizer/Dialect/FIRDialect.td"
include "flang/Optimizer/Dialect/FIRTypes.td"
// Base class for FIR operations.
// All operations automatically get a prefix of "fir.".
class fir_Op<string mnemonic, list<Trait> traits>
: Op<fir_Dialect, mnemonic, traits>;
// Base class for FIR operations that take a single argument
class fir_SimpleOp<string mnemonic, list<Trait> traits>
: fir_Op<mnemonic, traits> {
let assemblyFormat = [{
operands attr-dict `:` functional-type(operands, results)
}];
}
def fir_OneResultOpBuilder : OpBuilder<(ins
"mlir::Type":$resultType,
"mlir::ValueRange":$operands,
CArg<"llvm::ArrayRef<mlir::NamedAttribute>", "{}">:$attributes),
[{
if (resultType)
$_state.addTypes(resultType);
$_state.addOperands(operands);
$_state.addAttributes(attributes);
}]>;
// Base class of FIR operations that return 1 result
class fir_OneResultOp<string mnemonic, list<Trait> 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<Trait> traits = []> :
fir_SimpleOp<mnemonic, traits> {
let builders = [fir_OneResultOpBuilder];
}
//===----------------------------------------------------------------------===//
// Memory SSA operations
//===----------------------------------------------------------------------===//
def fir_AllocaOp : fir_Op<"alloca", [AttrSizedOperandSegments,
MemoryEffects<[MemAlloc<AutomaticAllocationScopeResource>]>]> {
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.
Fortran Semantics:
There is no language mechanism in Fortran to allocate space on the stack
like C's `alloca()` function. Therefore fir.alloca is not control-flow
dependent. However, the lifetime of a stack allocation is often limited to
a small region and a legal implementation may reuse stack storage in other
regions when there is no conflict. For example, take the following code
fragment.
```fortran
CALL foo(1)
CALL foo(2)
CALL foo(3)
```
A legal implementation can allocate a stack slot and initialize it with the
constant `1`, then pass that by reference to foo. Likewise for the second
and third calls to foo, each stack slot being initialized accordingly. It is
also a conforming implementation to reuse the same stack slot for all three
calls, just initializing each in turn. This is possible as the lifetime of
the copy of each constant need not exceed that of the CALL statement.
Indeed, a user would likely expect a good Fortran compiler to perform such
an optimization.
Until Fortran 2018, procedures defaulted to non-recursive. A legal
implementation could therefore convert stack allocations to global
allocations. Such a conversion effectively adds the SAVE attribute to all
variables.
Some temporary entities (large arrays) probably should not be stack
allocated as stack space can often be limited. A legal implementation can
convert these large stack allocations to heap allocations regardless of
whether the procedure is recursive or not.
The pinned attribute is used to flag fir.alloca operation in a specific
region and avoid them being hoisted in an alloca hoisting pass.
}];
let arguments = (ins
TypeAttr:$in_type,
OptionalAttr<StrAttr>:$uniq_name,
OptionalAttr<StrAttr>:$bindc_name,
UnitAttr:$pinned,
Variadic<AnyIntegerType>:$typeparams,
Variadic<AnyIntegerType>:$shape
);
let results = (outs fir_ReferenceType);
let hasCustomAssemblyFormat = 1;
let hasVerifier = 1;
let builders = [
OpBuilder<(ins "mlir::Type":$inType, "llvm::StringRef":$uniqName,
"llvm::StringRef":$bindcName, CArg<"mlir::ValueRange", "{}">:$typeparams,
CArg<"mlir::ValueRange", "{}">:$shape,
CArg<"llvm::ArrayRef<mlir::NamedAttribute>", "{}">:$attributes)>,
OpBuilder<(ins "mlir::Type":$inType, "llvm::StringRef":$uniqName,
"llvm::StringRef":$bindcName, "bool":$pinned,
CArg<"mlir::ValueRange", "{}">:$typeparams,
CArg<"mlir::ValueRange", "{}">:$shape,
CArg<"llvm::ArrayRef<mlir::NamedAttribute>", "{}">:$attributes)>,
OpBuilder<(ins "mlir::Type":$inType, "llvm::StringRef":$uniqName,
CArg<"mlir::ValueRange", "{}">:$typeparams,
CArg<"mlir::ValueRange", "{}">:$shape,
CArg<"llvm::ArrayRef<mlir::NamedAttribute>", "{}">:$attributes)>,
OpBuilder<(ins "mlir::Type":$inType, "llvm::StringRef":$uniqName,
"bool":$pinned, CArg<"mlir::ValueRange", "{}">:$typeparams,
CArg<"mlir::ValueRange", "{}">:$shape,
CArg<"llvm::ArrayRef<mlir::NamedAttribute>", "{}">:$attributes)>,
OpBuilder<(ins "mlir::Type":$inType, "bool":$pinned,
CArg<"mlir::ValueRange", "{}">:$typeparams,
CArg<"mlir::ValueRange", "{}">:$shape,
CArg<"llvm::ArrayRef<mlir::NamedAttribute>", "{}">:$attributes)>,
OpBuilder<(ins "mlir::Type":$inType,
CArg<"mlir::ValueRange", "{}">:$typeparams,
CArg<"mlir::ValueRange", "{}">:$shape,
CArg<"llvm::ArrayRef<mlir::NamedAttribute>", "{}">:$attributes)>];
let extraClassDeclaration = [{
mlir::Type getAllocatedType();
bool hasLenParams() { return !getTypeparams().empty(); }
bool hasShapeOperands() { return !getShape().empty(); }
unsigned numLenParams() { return getTypeparams().size(); }
operand_range getLenParams() { return getTypeparams(); }
unsigned numShapeOperands() { return getShape().size(); }
operand_range getShapeOperands() { return getShape(); }
static mlir::Type getRefTy(mlir::Type ty);
}];
}
def fir_AllocMemOp : fir_Op<"allocmem",
[MemoryEffects<[MemAlloc<DefaultResource>]>, AttrSizedOperandSegments]> {
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 arguments = (ins
TypeAttr:$in_type,
OptionalAttr<StrAttr>:$uniq_name,
OptionalAttr<StrAttr>:$bindc_name,
Variadic<AnyIntegerType>:$typeparams,
Variadic<AnyIntegerType>:$shape
);
let results = (outs fir_HeapType);
let hasCustomAssemblyFormat = 1;
let hasVerifier = 1;
let builders = [
OpBuilder<(ins "mlir::Type":$in_type, "llvm::StringRef":$uniq_name,
"llvm::StringRef":$bindc_name, CArg<"mlir::ValueRange", "{}">:$typeparams,
CArg<"mlir::ValueRange", "{}">:$shape,
CArg<"llvm::ArrayRef<mlir::NamedAttribute>", "{}">:$attributes)>,
OpBuilder<(ins "mlir::Type":$in_type, "llvm::StringRef":$uniq_name,
CArg<"mlir::ValueRange", "{}">:$typeparams,
CArg<"mlir::ValueRange", "{}">:$shape,
CArg<"llvm::ArrayRef<mlir::NamedAttribute>", "{}">:$attributes)>,
OpBuilder<(ins "mlir::Type":$in_type,
CArg<"mlir::ValueRange", "{}">:$typeparams,
CArg<"mlir::ValueRange", "{}">:$shape,
CArg<"llvm::ArrayRef<mlir::NamedAttribute>", "{}">:$attributes)>];
let extraClassDeclaration = [{
mlir::Type getAllocatedType();
bool hasLenParams() { return !getTypeparams().empty(); }
bool hasShapeOperands() { return !getShape().empty(); }
unsigned numLenParams() { return getTypeparams().size(); }
operand_range getLenParams() { return getTypeparams(); }
unsigned numShapeOperands() { return getShape().size(); }
operand_range getShapeOperands() { return getShape(); }
static mlir::Type getRefTy(mlir::Type ty);
}];
}
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 Arg<fir_HeapType, "", [MemFree]>:$heapref);
let assemblyFormat = "$heapref attr-dict `:` type($heapref)";
}
def fir_LoadOp : fir_OneResultOp<"load"> {
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 Arg<AnyReferenceLike, "", [MemRead]>:$memref);
let builders = [OpBuilder<(ins "mlir::Value":$refVal)>];
let hasCustomAssemblyFormat = 1;
let extraClassDeclaration = [{
static mlir::ParseResult getElementOf(mlir::Type &ele, mlir::Type ref);
}];
}
def fir_CharConvertOp : fir_Op<"char_convert", []> {
let summary = [{
Primitive to convert an entity of type CHARACTER from one KIND to a
different KIND.
}];
let description = [{
Copy a CHARACTER (must be in memory) of KIND _k1_ to a CHARACTER (also must
be in memory) of KIND _k2_ where _k1_ != _k2_ and the buffers do not
overlap. This latter restriction is unchecked, as the Fortran language
definition eliminates the overlapping in memory case.
The number of code points copied is specified explicitly as the second
argument. The length of the !fir.char type is ignored.
```mlir
fir.char_convert %1 for %2 to %3 : !fir.ref<!fir.char<1,?>>, i32,
!fir.ref<!fir.char<2,20>>
```
Should future support for encodings other than ASCII be supported, codegen
can generate a call to a runtime helper routine which will map the code
points from UTF-8 to UCS-2, for example. Such remappings may not always
be possible as they may involve the creation of more code points than the
`count` limit. These details are left as future to-dos.
}];
let arguments = (ins
Arg<AnyReferenceLike, "", [MemRead]>:$from,
AnyIntegerType:$count,
Arg<AnyReferenceLike, "", [MemWrite]>:$to
);
let assemblyFormat = [{
$from `for` $count `to` $to attr-dict `:` type(operands)
}];
let hasVerifier = 1;
}
def fir_StoreOp : fir_Op<"store", []> {
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,
Arg<AnyReferenceLike, "", [MemWrite]>:$memref);
let hasCustomAssemblyFormat = 1;
let hasVerifier = 1;
let extraClassDeclaration = [{
static mlir::Type elementType(mlir::Type refType);
}];
}
def fir_SaveResultOp : fir_Op<"save_result", [AttrSizedOperandSegments]> {
let summary = [{
save an array, box, or record function result SSA-value to a memory location
}];
let description = [{
Save the result of a function returning an array, box, or record type value
into a memory location given the shape and length parameters of the result.
Function results of type fir.box, fir.array, or fir.rec are abstract values
that require a storage to be manipulated on the caller side. This operation
allows associating such abstract result to a storage. In later lowering of
the function interfaces, this storage might be used to pass the result in
memory.
For arrays, result, it is required to provide the shape of the result. For
character arrays and derived types with length parameters, the length
parameter values must be provided.
The fir.save_result associated to a function call must immediately follow
the call and be in the same block.
```mlir
%buffer = fir.alloca fir.array<?xf32>, %c100
%shape = fir.shape %c100
%array_result = fir.call @foo() : () -> fir.array<?xf32>
fir.save_result %array_result to %buffer(%shape)
%coor = fir.array_coor %buffer%(%shape), %c5
%fifth_element = fir.load %coor : f32
```
The above fir.save_result allows saving a fir.array function result into
a buffer to later access its 5th element.
}];
let arguments = (ins ArrayOrBoxOrRecord:$value,
Arg<AnyReferenceLike, "", [MemWrite]>:$memref,
Optional<AnyShapeType>:$shape,
Variadic<AnyIntegerType>:$typeparams);
let assemblyFormat = [{
$value `to` $memref (`(` $shape^ `)`)? (`typeparams` $typeparams^)?
attr-dict `:` type(operands)
}];
let hasVerifier = 1;
}
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";
// Note: we allow `undef : ref<T>` since it is a possible from transformations.
let hasVerifier = 0;
}
def fir_ZeroOp : fir_OneResultOp<"zero_bits", [NoSideEffect]> {
let summary = "explicit polymorphic zero value of some type";
let description = [{
Constructs an ssa-value of the specified type with a value of zero for all
bits.
```mlir
%a = fir.zero_bits !fir.box<!fir.array<10 x !fir.type<T>>>
```
The example creates a value of type box where all bits are zero.
}];
let results = (outs AnyType:$intype);
let assemblyFormat = "type($intype) attr-dict";
}
//===----------------------------------------------------------------------===//
// Terminator operations
//===----------------------------------------------------------------------===//
class fir_SwitchTerminatorOp<string mnemonic, list<Trait> 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 getCases().size();
}
// The selector is the value being tested to determine the destination
mlir::Value getSelector(llvm::ArrayRef<mlir::Value> operands) {
return operands[0];
}
mlir::Value getSelector(mlir::ValueRange operands) {
return operands.front();
}
// The number of blocks that may be branched to
unsigned getNumDest() { return (*this)->getNumSuccessors(); }
llvm::Optional<mlir::OperandRange> getCompareOperands(unsigned cond);
llvm::Optional<llvm::ArrayRef<mlir::Value>> getCompareOperands(
llvm::ArrayRef<mlir::Value> operands, unsigned cond);
llvm::Optional<mlir::ValueRange> getCompareOperands(
mlir::ValueRange operands, unsigned cond);
llvm::Optional<llvm::ArrayRef<mlir::Value>> getSuccessorOperands(
llvm::ArrayRef<mlir::Value> operands, unsigned cond);
llvm::Optional<mlir::ValueRange> getSuccessorOperands(
mlir::ValueRange 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);
}
mlir::ArrayAttr getCases() {
return (*this)->getAttrOfType<mlir::ArrayAttr>(getCasesAttr());
}
unsigned targetOffsetSize();
}];
}
class fir_IntegralSwitchTerminatorOp<string mnemonic,
list<Trait> traits = []> : fir_SwitchTerminatorOp<mnemonic, traits> {
let skipDefaultBuilders = 1;
let builders = [OpBuilder<(ins "mlir::Value":$selector,
"llvm::ArrayRef<int64_t>":$compareOperands,
"llvm::ArrayRef<mlir::Block *>":$destinations,
CArg<"llvm::ArrayRef<mlir::ValueRange>", "{}">:$destOperands,
CArg<"llvm::ArrayRef<mlir::NamedAttribute>", "{}">:$attributes),
[{
$_state.addOperands(selector);
llvm::SmallVector<mlir::Attribute> ivalues;
for (auto iv : compareOperands)
ivalues.push_back($_builder.getI64IntegerAttr(iv));
ivalues.push_back($_builder.getUnitAttr());
$_state.addAttribute(getCasesAttr(), $_builder.getArrayAttr(ivalues));
const auto count = destinations.size();
for (auto d : destinations)
$_state.addSuccessors(d);
const auto opCount = destOperands.size();
llvm::SmallVector<int32_t> argOffs;
int32_t sumArgs = 0;
for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
if (i < opCount) {
$_state.addOperands(destOperands[i]);
const auto argSz = destOperands[i].size();
argOffs.push_back(argSz);
sumArgs += argSz;
} else {
argOffs.push_back(0);
}
}
$_state.addAttribute(getOperandSegmentSizeAttr(),
$_builder.getI32VectorAttr({1, 0, sumArgs}));
$_state.addAttribute(getTargetOffsetAttr(),
$_builder.getI32VectorAttr(argOffs));
$_state.addAttributes(attributes);
}]
>];
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]
```
}];
let hasCustomAssemblyFormat = 1;
let hasVerifier = 1;
}
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]
```
}];
let hasCustomAssemblyFormat = 1;
let hasVerifier = 1;
}
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<(ins "mlir::Value":$selector,
"llvm::ArrayRef<mlir::Attribute>":$compareAttrs,
"llvm::ArrayRef<mlir::ValueRange>":$cmpOperands,
"llvm::ArrayRef<mlir::Block *>":$destinations,
CArg<"llvm::ArrayRef<mlir::ValueRange>", "{}">:$destOperands,
CArg<"llvm::ArrayRef<mlir::NamedAttribute>", "{}">:$attributes)>,
OpBuilder<(ins "mlir::Value":$selector,
"llvm::ArrayRef<mlir::Attribute>":$compareAttrs,
"llvm::ArrayRef<mlir::Value>":$cmpOpList,
"llvm::ArrayRef<mlir::Block *>":$destinations,
CArg<"llvm::ArrayRef<mlir::ValueRange>", "{}">:$destOperands,
CArg<"llvm::ArrayRef<mlir::NamedAttribute>", "{}">:$attributes)>];
let hasCustomAssemblyFormat = 1;
let hasVerifier = 1;
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<(ins "mlir::Value":$selector,
"llvm::ArrayRef<mlir::Attribute>":$typeOperands,
"llvm::ArrayRef<mlir::Block *>":$destinations,
CArg<"llvm::ArrayRef<mlir::ValueRange>", "{}">:$destOperands,
CArg<"llvm::ArrayRef<mlir::NamedAttribute>", "{}">:$attributes)>];
let hasCustomAssemblyFormat = 1;
let hasVerifier = 1;
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 assemblyFormat = [{ attr-dict }];
}
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> {
%0 = arith.constant 45 : i32
%1 = arith.constant 100.0 : f32
%2 = fir.undefined tuple<i32, f32>
%3 = arith.constant 0 : index
%4 = fir.insert_value %2, %0, %3 : (tuple<i32, f32>, i32, index) -> tuple<i32, f32>
%5 = arith.constant 1 : index
%6 = fir.insert_value %4, %1, %5 : (tuple<i32, f32>, f32, index) -> tuple<i32, f32>
fir.has_value %6 : tuple<i32, f32>
}
```
}];
let arguments = (ins AnyType:$resval);
let assemblyFormat = "$resval attr-dict `:` type($resval)";
}
//===----------------------------------------------------------------------===//
// Operations on !fir.box<T> type objects
//===----------------------------------------------------------------------===//
def fir_EmboxOp : fir_Op<"embox", [NoSideEffect, AttrSizedOperandSegments]> {
let summary = "boxes a given reference and (optional) dimension information";
let description = [{
Create a boxed reference value. In Fortran, the implementation can require
extra information about an entity, such as its type, rank, etc. This
auxilliary information is packaged and abstracted as a value with box type
by the calling routine. (In Fortran, these are called descriptors.)
```mlir
%c1 = arith.constant 1 : index
%c10 = arith.constant 10 : index
%5 = ... : !fir.ref<!fir.array<10 x i32>>
%6 = fir.embox %5 : (!fir.ref<!fir.array<10 x i32>>) -> !fir.box<!fir.array<10 x i32>>
```
The descriptor tuple may contain additional implementation-specific
information through the use of additional attributes.
Specifically,
- shape: emboxing an array may require shape information (an array's
lower bounds and extents may not be known until runtime),
- slice: an array section can be described with a slice triple,
- typeparams: for emboxing a derived type with LEN type parameters,
- accessMap: unused/experimental.
}];
let arguments = (ins
AnyReferenceLike:$memref,
Optional<AnyShapeType>:$shape,
Optional<fir_SliceType>:$slice,
Variadic<AnyIntegerType>:$typeparams,
OptionalAttr<AffineMapAttr>:$accessMap
);
let results = (outs fir_BoxType);
let builders = [
OpBuilder<(ins "llvm::ArrayRef<mlir::Type>":$resultTypes,
"mlir::Value":$memref, CArg<"mlir::Value", "{}">:$shape,
CArg<"mlir::Value", "{}">:$slice,
CArg<"mlir::ValueRange", "{}">:$typeparams),
[{ return build($_builder, $_state, resultTypes, memref, shape, slice,
typeparams, mlir::AffineMapAttr{}); }]>
];
let assemblyFormat = [{
$memref (`(` $shape^ `)`)? (`[` $slice^ `]`)? (`typeparams` $typeparams^)?
(`map` $accessMap^)? attr-dict `:` functional-type(operands, results)
}];
let hasVerifier = 1;
let extraClassDeclaration = [{
bool hasLenParams() { return !getTypeparams().empty(); }
unsigned numLenParams() { return getTypeparams().size(); }
}];
}
def fir_ReboxOp : fir_Op<"rebox", [NoSideEffect, AttrSizedOperandSegments]> {
let summary =
"create a box given another box and (optional) dimension information";
let description = [{
Create a new boxed reference value from another box. This is meant to be
used when the taking a reference to part of a boxed value, or to an entire
boxed value with new shape or type information.
The new extra information can be:
- new shape information (new lower bounds, new rank, or new extents.
New rank/extents can only be provided if the original fir.box is
contiguous in all dimension but maybe the first row). The shape
operand must be provided to set new shape information.
- new type (only for derived types). It is possible to set the dynamic
type of the new box to one of the parent types of the input box dynamic
type. Type parameters cannot be changed. This change is reflected in
the requested result type of the new box.
A slice argument can be provided to build a reference to part of a boxed
value. In this case, the shape operand must be absent or be a fir.shift
that can be used to provide a non default origin for the slice.
The following example illustrates creating a fir.box for x(10:33:2)
where x is described by a fir.box and has non default lower bounds,
and then applying a new 2-dimension shape to this fir.box.
```mlir
%0 = fir.slice %c10, %c33, %c2 : (index, index, index) -> !fir.slice<1>
%1 = fir.shift %c0 : (index) -> !fir.shift<1>
%2 = fir.rebox %x(%1) [%0] : (!fir.box<!fir.array<?xf32>>, !fir.shift<1>, !fir.slice<1>) -> !fir.box<!fir.array<?xf32>>
%3 = fir.shape %c3, %c4 : (index, index) -> !fir.shape<2>
%4 = fir.rebox %2(%3) : (!fir.box<!fir.array<?xf32>>, !fir.shape<2>) -> !fir.box<!fir.array<?x?xf32>>
```
}];
let arguments = (ins
fir_BoxType:$box,
Optional<AnyShapeOrShiftType>:$shape,
Optional<fir_SliceType>:$slice
);
let results = (outs fir_BoxType);
let assemblyFormat = [{
$box (`(` $shape^ `)`)? (`[` $slice^ `]`)? attr-dict `:` functional-type(operands, results)
}];
let hasVerifier = 1;
}
def fir_EmboxCharOp : fir_Op<"emboxchar", [NoSideEffect]> {
let summary = "boxes a given CHARACTER reference and its LEN parameter";
let description = [{
Create a boxed CHARACTER value. The CHARACTER type has the LEN type
parameter, the value of which may only be known at runtime. Therefore,
a variable of type CHARACTER has both its data reference as well as a
LEN type parameter.
```fortran
CHARACTER(LEN=10) :: var
```
```mlir
%4 = ... : !fir.ref<!fir.array<10 x !fir.char<1>>>
%5 = arith.constant 10 : i32
%6 = fir.emboxchar %4, %5 : (!fir.ref<!fir.array<10 x !fir.char<1>>>, i32) -> !fir.boxchar<1>
```
In the above `%4` is a memory reference to a buffer of 10 CHARACTER units.
This buffer and its LEN value (10) are wrapped into a pair in `%6`.
}];
let arguments = (ins AnyReferenceLike:$memref, AnyIntegerLike:$len);
let results = (outs fir_BoxCharType);
let assemblyFormat = [{
$memref `,` $len attr-dict `:` functional-type(operands, results)
}];
let hasVerifier = 1;
}
def fir_EmboxProcOp : fir_Op<"emboxproc", [NoSideEffect]> {
let summary = "boxes a given procedure and optional host context";
let description = [{
Creates an abstract encapsulation of a PROCEDURE POINTER along with an
optional pointer to a host instance context. If the pointer is not to an
internal procedure or the internal procedure does not need a host context
then the form takes only the procedure's symbol.
```mlir
%0 = fir.emboxproc @f : ((i32) -> i32) -> !fir.boxproc<(i32) -> i32>
```
An internal procedure requiring a host instance for correct execution uses
the second form. The closure of the host procedure's state is passed as a
reference to a tuple. It is the responsibility of the host to manage the
context's values accordingly, up to and including inhibiting register
promotion of local values.
```mlir
%4 = ... : !fir.ref<tuple<i32, i32>>
%5 = fir.emboxproc @g, %4 : ((i32) -> i32, !fir.ref<tuple<i32, i32>>) -> !fir.boxproc<(i32) -> i32>
```
}];
let arguments = (ins SymbolRefAttr:$funcname, AnyReferenceLike:$host);
let results = (outs fir_BoxProcType);
let hasCustomAssemblyFormat = 1;
let hasVerifier = 1;
}
def fir_UnboxCharOp : fir_SimpleOp<"unboxchar", [NoSideEffect]> {
let summary = "unbox a boxchar value into a pair value";
let description = [{
Unboxes a value of `boxchar` type into a pair consisting of a memory
reference to the CHARACTER data and the LEN type parameter.
```mlir
%45 = ... : !fir.boxchar<1>
%46:2 = fir.unboxchar %45 : (!fir.boxchar<1>) -> (!fir.ref<!fir.char<1>>, i32)
```
}];
let arguments = (ins fir_BoxCharType:$boxchar);
let results = (outs fir_ReferenceType, AnyIntegerLike);
}
def fir_UnboxProcOp : fir_SimpleOp<"unboxproc", [NoSideEffect]> {
let summary = "unbox a boxproc value into a pair value";
let description = [{
Unboxes a value of `boxproc` type into a pair consisting of a procedure
pointer and a pointer to a host context.
```mlir
%47 = ... : !fir.boxproc<() -> i32>
%48:2 = fir.unboxproc %47 : (!fir.ref<() -> i32>, !fir.ref<tuple<f32, i32>>)
```
}];
let hasVerifier = 1;
let arguments = (ins fir_BoxProcType:$boxproc);
let results = (outs FunctionType, fir_ReferenceType:$refTuple);
}
def fir_BoxAddrOp : fir_SimpleOneResultOp<"box_addr", [NoSideEffect]> {
let summary = "return a memory reference to the boxed value";
let description = [{
This operator is overloaded to work with values of type `box`,
`boxchar`, and `boxproc`. The result for each of these
cases, respectively, is the address of the data, the address of the
`CHARACTER` data, and the address of the procedure.
```mlir
%51 = fir.box_addr %box : (!fir.box<f64>) -> !fir.ref<f64>
%52 = fir.box_addr %boxchar : (!fir.boxchar<1>) -> !fir.ref<!fir.char<1>>
%53 = fir.box_addr %boxproc : (!fir.boxproc<!P>) -> !fir.ref<!P>
```
}];
let arguments = (ins fir_BoxType:$val);
let results = (outs AnyReferenceLike);
let hasFolder = 1;
}
def fir_BoxCharLenOp : fir_SimpleOp<"boxchar_len", [NoSideEffect]> {
let summary = "return the LEN type parameter from a boxchar value";
let description = [{
Extracts the LEN type parameter from a `boxchar` value.
```mlir
%45 = ... : !boxchar<1> // CHARACTER(20)
%59 = fir.boxchar_len %45 : (!fir.boxchar<1>) -> i64 // len=20
```
}];
let arguments = (ins fir_BoxCharType:$val);
let results = (outs AnyIntegerLike);
let hasFolder = 1;
}
def fir_BoxDimsOp : fir_Op<"box_dims", [NoSideEffect]> {
let summary = "return the dynamic dimension information for the boxed value";
let description = [{
Returns the triple of lower bound, extent, and stride for `dim` dimension
of `val`, which must have a `box` type. The dimensions are enumerated from
left to right from 0 to rank-1. This operation has undefined behavior if
`dim` is out of bounds.
```mlir