/
MemRefOps.td
2123 lines (1766 loc) · 81.2 KB
/
MemRefOps.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
//===- MemRefOps.td - MemRef op 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
//
//===----------------------------------------------------------------------===//
#ifndef MEMREF_OPS
#define MEMREF_OPS
include "mlir/Dialect/Arith/IR/ArithBase.td"
include "mlir/Dialect/MemRef/IR/MemRefBase.td"
include "mlir/Interfaces/CastInterfaces.td"
include "mlir/Interfaces/ControlFlowInterfaces.td"
include "mlir/Interfaces/CopyOpInterface.td"
include "mlir/Interfaces/ShapedOpInterfaces.td"
include "mlir/Interfaces/SideEffectInterfaces.td"
include "mlir/Interfaces/ViewLikeInterface.td"
include "mlir/IR/OpAsmInterface.td"
include "mlir/IR/SymbolInterfaces.td"
/// A TypeAttr for memref types.
def MemRefTypeAttr
: TypeAttrBase<"::mlir::MemRefType", "memref type attribute"> {
let constBuilderCall = "::mlir::TypeAttr::get($0)";
}
class MemRef_Op<string mnemonic, list<Trait> traits = []>
: Op<MemRef_Dialect, mnemonic, traits>;
// Base class for ops with static/dynamic offset, sizes and strides
// attributes/arguments.
class MemRef_OpWithOffsetSizesAndStrides<string mnemonic,
list<Trait> traits = []>
: MemRef_Op<mnemonic, traits> {
code extraBaseClassDeclaration = [{
/// Returns the dynamic sizes for this subview operation if specified.
::mlir::Operation::operand_range getDynamicSizes() { return getSizes(); }
/// Return the list of Range (i.e. offset, size, stride). Each
/// Range entry contains either the dynamic value or a ConstantIndexOp
/// constructed with `b` at location `loc`.
::mlir::SmallVector<::mlir::Range, 8> getOrCreateRanges(
::mlir::OpBuilder &b, ::mlir::Location loc) {
return ::mlir::getOrCreateRanges(*this, b, loc);
}
}];
}
//===----------------------------------------------------------------------===//
// AllocLikeOp
//===----------------------------------------------------------------------===//
// Base class for memref allocating ops: alloca and alloc.
//
// %0 = alloclike(%m)[%s] : memref<8x?xf32, affine_map<(d0, d1)[s0] -> (d0 + s0, d1)>>
//
class AllocLikeOp<string mnemonic,
Resource resource,
list<Trait> traits = []> :
MemRef_Op<mnemonic,
!listconcat([
AttrSizedOperandSegments
], traits)> {
let arguments = (ins Variadic<Index>:$dynamicSizes,
// The symbolic operands (the ones in square brackets)
// bind to the symbols of the memref's layout map.
Variadic<Index>:$symbolOperands,
ConfinedAttr<OptionalAttr<I64Attr>,
[IntMinValue<0>]>:$alignment);
let results = (outs Res<AnyMemRef, "", [MemAlloc<resource>]>:$memref);
let builders = [
OpBuilder<(ins "MemRefType":$memrefType,
CArg<"IntegerAttr", "IntegerAttr()">:$alignment), [{
return build($_builder, $_state, memrefType, {}, alignment);
}]>,
OpBuilder<(ins "MemRefType":$memrefType, "ValueRange":$dynamicSizes,
CArg<"IntegerAttr", "IntegerAttr()">:$alignment), [{
return build($_builder, $_state, memrefType, dynamicSizes, {}, alignment);
}]>,
OpBuilder<(ins "MemRefType":$memrefType, "ValueRange":$dynamicSizes,
"ValueRange":$symbolOperands,
CArg<"IntegerAttr", "{}">:$alignment), [{
$_state.types.push_back(memrefType);
$_state.addOperands(dynamicSizes);
$_state.addOperands(symbolOperands);
$_state.addAttribute(getOperandSegmentSizeAttr(),
$_builder.getDenseI32ArrayAttr({
static_cast<int32_t>(dynamicSizes.size()),
static_cast<int32_t>(symbolOperands.size())}));
if (alignment)
$_state.addAttribute(getAlignmentAttrStrName(), alignment);
}]>];
let extraClassDeclaration = [{
static StringRef getAlignmentAttrStrName() { return "alignment"; }
MemRefType getType() { return getResult().getType().cast<MemRefType>(); }
}];
let assemblyFormat = [{
`(`$dynamicSizes`)` (`` `[` $symbolOperands^ `]`)? attr-dict `:` type($memref)
}];
let hasCanonicalizer = 1;
let hasVerifier = 1;
}
//===----------------------------------------------------------------------===//
// AssumeAlignmentOp
//===----------------------------------------------------------------------===//
def AssumeAlignmentOp : MemRef_Op<"assume_alignment"> {
let summary =
"assertion that gives alignment information to the input memref";
let description = [{
The `assume_alignment` operation takes a memref and an integer of alignment
value, and internally annotates the buffer with the given alignment. If
the buffer isn't aligned to the given alignment, the behavior is undefined.
This operation doesn't affect the semantics of a correct program. It's for
optimization only, and the optimization is best-effort.
}];
let arguments = (ins AnyMemRef:$memref,
ConfinedAttr<I32Attr, [IntPositive]>:$alignment);
let results = (outs);
let assemblyFormat = "$memref `,` $alignment attr-dict `:` type($memref)";
let hasVerifier = 1;
}
//===----------------------------------------------------------------------===//
// AllocOp
//===----------------------------------------------------------------------===//
def MemRef_AllocOp : AllocLikeOp<"alloc", DefaultResource, [
DeclareOpInterfaceMethods<OpAsmOpInterface, ["getAsmResultNames"]>]> {
let summary = "memory allocation operation";
let description = [{
The `alloc` operation allocates a region of memory, as specified by its
memref type.
Example:
```mlir
%0 = memref.alloc() : memref<8x64xf32, 1>
```
The optional list of dimension operands are bound to the dynamic dimensions
specified in its memref type. In the example below, the ssa value '%d' is
bound to the second dimension of the memref (which is dynamic).
```mlir
%0 = memref.alloc(%d) : memref<8x?xf32, 1>
```
The optional list of symbol operands are bound to the symbols of the
memrefs affine map. In the example below, the ssa value '%s' is bound to
the symbol 's0' in the affine map specified in the allocs memref type.
```mlir
%0 = memref.alloc()[%s] : memref<8x64xf32,
affine_map<(d0, d1)[s0] -> ((d0 + s0), d1)>, 1>
```
This operation returns a single ssa value of memref type, which can be used
by subsequent load and store operations.
The optional `alignment` attribute may be specified to ensure that the
region of memory that will be indexed is aligned at the specified byte
boundary.
```mlir
%0 = memref.alloc()[%s] {alignment = 8} :
memref<8x64xf32, affine_map<(d0, d1)[s0] -> ((d0 + s0), d1)>, 1>
```
}];
let hasVerifier = 1;
}
//===----------------------------------------------------------------------===//
// ReallocOp
//===----------------------------------------------------------------------===//
def MemRef_ReallocOp : MemRef_Op<"realloc"> {
let summary = "memory reallocation operation";
let description = [{
The `realloc` operation changes the size of a memory region. The memory
region is specified by a 1D source memref and the size of the new memory
region is specified by a 1D result memref type and an optional dynamic Value
of `Index` type. The source and the result memref must be in the same memory
space and have the same element type.
The operation may move the memory region to a new location. In this case,
the content of the memory block is preserved up to the lesser of the new
and old sizes. If the new size if larger, the value of the extended memory
is undefined. This is consistent with the ISO C realloc.
The operation returns an SSA value for the memref.
Example:
```mlir
%0 = memref.realloc %src : memref<64xf32> to memref<124xf32>
```
The source memref may have a dynamic shape, in which case, the compiler will
generate code to extract its size from the runtime data structure for the
memref.
```mlir
%1 = memref.realloc %src : memref<?xf32> to memref<124xf32>
```
If the result memref has a dynamic shape, a result dimension operand is
needed to spefify its dynamic dimension. In the example below, the ssa value
'%d' specifies the unknown dimension of the result memref.
```mlir
%2 = memref.realloc %src(%d) : memref<?xf32> to memref<?xf32>
```
An optional `alignment` attribute may be specified to ensure that the
region of memory that will be indexed is aligned at the specified byte
boundary. This is consistent with the fact that memref.alloc supports such
an optional alignment attribute. Note that in ISO C standard, neither alloc
nor realloc supports alignment, though there is aligned_alloc but not
aligned_realloc.
```mlir
%3 = memref.ralloc %src {alignment = 8} : memref<64xf32> to memref<124xf32>
```
Referencing the memref through the old SSA value after realloc is undefined
behavior.
```mlir
%new = memref.realloc %old : memref<64xf32> to memref<124xf32>
%4 = memref.load %new[%index] // ok
%5 = memref.load %old[%index] // undefined behavior
```
}];
let arguments = (ins MemRefRankOf<[AnyType], [1]>:$source,
Optional<Index>:$dynamicResultSize,
ConfinedAttr<OptionalAttr<I64Attr>,
[IntMinValue<0>]>:$alignment);
let results = (outs MemRefRankOf<[AnyType], [1]>);
let builders = [
OpBuilder<(ins "MemRefType":$resultType,
"Value":$source,
CArg<"Value", "Value()">:$dynamicResultSize), [{
return build($_builder, $_state, resultType, source, dynamicResultSize,
IntegerAttr());
}]>];
let extraClassDeclaration = [{
/// The result of a realloc is always a memref.
MemRefType getType() { return getResult().getType().cast<MemRefType>(); }
}];
let assemblyFormat = [{
$source (`(` $dynamicResultSize^ `)`)? attr-dict
`:` type($source) `to` type(results)
}];
let hasCanonicalizer = 1;
let hasVerifier = 1;
}
//===----------------------------------------------------------------------===//
// AllocaOp
//===----------------------------------------------------------------------===//
def MemRef_AllocaOp : AllocLikeOp<"alloca", AutomaticAllocationScopeResource,[
DeclareOpInterfaceMethods<OpAsmOpInterface, ["getAsmResultNames"]>]> {
let summary = "stack memory allocation operation";
let description = [{
The `alloca` operation allocates memory on the stack, to be automatically
released when control transfers back from the region of its closest
surrounding operation with an
[`AutomaticAllocationScope`](../Traits.md/#automaticallocationscope) trait.
The amount of memory allocated is specified by its memref and additional
operands. For example:
```mlir
%0 = memref.alloca() : memref<8x64xf32>
```
The optional list of dimension operands are bound to the dynamic dimensions
specified in its memref type. In the example below, the SSA value '%d' is
bound to the second dimension of the memref (which is dynamic).
```mlir
%0 = memref.alloca(%d) : memref<8x?xf32>
```
The optional list of symbol operands are bound to the symbols of the
memref's affine map. In the example below, the SSA value '%s' is bound to
the symbol 's0' in the affine map specified in the allocs memref type.
```mlir
%0 = memref.alloca()[%s] : memref<8x64xf32,
affine_map<(d0, d1)[s0] -> ((d0 + s0), d1)>>
```
This operation returns a single SSA value of memref type, which can be used
by subsequent load and store operations. An optional alignment attribute, if
specified, guarantees alignment at least to that boundary. If not specified,
an alignment on any convenient boundary compatible with the type will be
chosen.
}];
let hasVerifier = 1;
}
//===----------------------------------------------------------------------===//
// AllocaScopeOp
//===----------------------------------------------------------------------===//
def MemRef_AllocaScopeOp : MemRef_Op<"alloca_scope",
[AutomaticAllocationScope,
DeclareOpInterfaceMethods<RegionBranchOpInterface>,
SingleBlockImplicitTerminator<"AllocaScopeReturnOp">,
RecursiveSideEffects,
NoRegionArguments]> {
let summary = "explicitly delimited scope for stack allocation";
let description = [{
The `memref.alloca_scope` operation represents an explicitly-delimited
scope for the alloca allocations. Any `memref.alloca` operations that are
used within this scope are going to be cleaned up automatically once
the control-flow exits the nested region. For example:
```mlir
memref.alloca_scope {
%myalloca = memref.alloca(): memref<4x3xf32>
...
}
```
Here, `%myalloca` memref is valid within the explicitly delimited scope
and is automatically deallocated at the end of the given region. Conceptually,
`memref.alloca_scope` is a passthrough operation with
`AutomaticAllocationScope` that spans the body of the region within the operation.
`memref.alloca_scope` may also return results that are defined in the nested
region. To return a value, one should use `memref.alloca_scope.return`
operation:
```mlir
%result = memref.alloca_scope {
...
memref.alloca_scope.return %value
}
```
If `memref.alloca_scope` returns no value, the `memref.alloca_scope.return ` can
be left out, and will be inserted implicitly.
}];
let results = (outs Variadic<AnyType>:$results);
let regions = (region SizedRegion<1>:$bodyRegion);
let hasCustomAssemblyFormat = 1;
let hasCanonicalizer = 1;
}
//===----------------------------------------------------------------------===//
// AllocaScopeReturnOp
//===----------------------------------------------------------------------===//
def MemRef_AllocaScopeReturnOp : MemRef_Op<"alloca_scope.return",
[HasParent<"AllocaScopeOp">,
NoSideEffect,
ReturnLike,
Terminator]> {
let summary = "terminator for alloca_scope operation";
let description = [{
`memref.alloca_scope.return` operation returns zero or more SSA values
from the region within `memref.alloca_scope`. If no values are returned,
the return operation may be omitted. Otherwise, it has to be present
to indicate which values are going to be returned. For example:
```mlir
memref.alloca_scope.return %value
```
}];
let arguments = (ins Variadic<AnyType>:$results);
let builders = [OpBuilder<(ins), [{ /*nothing to do */ }]>];
let assemblyFormat = "attr-dict ($results^ `:` type($results))?";
}
//===----------------------------------------------------------------------===//
// CastOp
//===----------------------------------------------------------------------===//
def MemRef_CastOp : MemRef_Op<"cast", [
DeclareOpInterfaceMethods<CastOpInterface>,
DeclareOpInterfaceMethods<OpAsmOpInterface, ["getAsmResultNames"]>,
MemRefsNormalizable,
NoSideEffect,
SameOperandsAndResultShape,
ViewLikeOpInterface
]> {
let summary = "memref cast operation";
let description = [{
Syntax:
```
operation ::= ssa-id `=` `memref.cast` ssa-use `:` type `to` type
```
The `memref.cast` operation converts a memref from one type to an equivalent
type with a compatible shape. The source and destination types are
compatible if:
a. Both are ranked memref types with the same element type, address space,
and rank and:
1. Both have the same layout or both have compatible strided layouts.
2. The individual sizes (resp. offset and strides in the case of strided
memrefs) may convert constant dimensions to dynamic dimensions and
vice-versa.
If the cast converts any dimensions from an unknown to a known size, then it
acts as an assertion that fails at runtime if the dynamic dimensions
disagree with resultant destination size.
Example:
```mlir
// Assert that the input dynamic shape matches the destination static shape.
%2 = memref.cast %1 : memref<?x?xf32> to memref<4x4xf32>
// Erase static shape information, replacing it with dynamic information.
%3 = memref.cast %1 : memref<4xf32> to memref<?xf32>
// The same holds true for offsets and strides.
// Assert that the input dynamic shape matches the destination static stride.
%4 = memref.cast %1 : memref<12x4xf32, strided<[?, ?], offset: ?>> to
memref<12x4xf32, strided<[4, 1], offset: 5>>
// Erase static offset and stride information, replacing it with
// dynamic information.
%5 = memref.cast %1 : memref<12x4xf32, strided<[4, 1], offset: 5>> to
memref<12x4xf32, strided<[?, ?], offset: ?>>
```
b. Either or both memref types are unranked with the same element type, and
address space.
Example:
```mlir
Cast to concrete shape.
%4 = memref.cast %1 : memref<*xf32> to memref<4x?xf32>
Erase rank information.
%5 = memref.cast %1 : memref<4x?xf32> to memref<*xf32>
```
}];
let arguments = (ins AnyRankedOrUnrankedMemRef:$source);
let results = (outs AnyRankedOrUnrankedMemRef:$dest);
let assemblyFormat = "$source attr-dict `:` type($source) `to` type($dest)";
let extraClassDeclaration = [{
/// Fold the given CastOp into consumer op.
static bool canFoldIntoConsumerOp(CastOp castOp);
Value getViewSource() { return getSource(); }
}];
let hasFolder = 1;
}
//===----------------------------------------------------------------------===//
// CopyOp
//===----------------------------------------------------------------------===//
def CopyOp : MemRef_Op<"copy", [CopyOpInterface, SameOperandsElementType,
SameOperandsShape]> {
let description = [{
Copies the data from the source to the destination memref.
Usage:
```mlir
memref.copy %arg0, %arg1 : memref<?xf32> to memref<?xf32>
```
Source and destination are expected to have the same element type and shape.
Otherwise, the result is undefined. They may have different layouts.
}];
let arguments = (ins Arg<AnyRankedOrUnrankedMemRef, "the memref to copy from",
[MemRead]>:$source,
Arg<AnyRankedOrUnrankedMemRef, "the memref to copy to",
[MemWrite]>:$target);
let assemblyFormat = [{
$source `,` $target attr-dict `:` type($source) `to` type($target)
}];
let hasCanonicalizer = 1;
let hasFolder = 1;
}
//===----------------------------------------------------------------------===//
// DeallocOp
//===----------------------------------------------------------------------===//
def MemRef_DeallocOp : MemRef_Op<"dealloc", [MemRefsNormalizable]> {
let summary = "memory deallocation operation";
let description = [{
The `dealloc` operation frees the region of memory referenced by a memref
which was originally created by the `alloc` operation.
The `dealloc` operation should not be called on memrefs which alias an
alloc'd memref (e.g. memrefs returned by `view` operations).
Example:
```mlir
%0 = memref.alloc() : memref<8x64xf32, affine_map<(d0, d1) -> (d0, d1), 1>>
memref.dealloc %0 : memref<8x64xf32, affine_map<(d0, d1) -> (d0, d1), 1>>
```
}];
let arguments = (ins Arg<AnyRankedOrUnrankedMemRef, "", [MemFree]>:$memref);
let hasFolder = 1;
let assemblyFormat = "$memref attr-dict `:` type($memref)";
}
//===----------------------------------------------------------------------===//
// DimOp
//===----------------------------------------------------------------------===//
def MemRef_DimOp : MemRef_Op<"dim", [
DeclareOpInterfaceMethods<OpAsmOpInterface, ["getAsmResultNames"]>,
MemRefsNormalizable,
NoSideEffect,
ShapedDimOpInterface]> {
let summary = "dimension index operation";
let description = [{
The `dim` operation takes a memref and a dimension operand of type `index`.
It returns the size of the requested dimension of the given memref.
If the dimension index is out of bounds the behavior is undefined.
The specified memref type is that of the first operand.
Example:
```mlir
// Always returns 4, can be constant folded:
%c0 = arith.constant 0 : index
%x = memref.dim %A, %c0 : memref<4 x ? x f32>
// Returns the dynamic dimension of %A.
%c1 = arith.constant 1 : index
%y = memref.dim %A, %c1 : memref<4 x ? x f32>
// Equivalent generic form:
%x = "memref.dim"(%A, %c0) : (memref<4 x ? x f32>, index) -> index
%y = "memref.dim"(%A, %c1) : (memref<4 x ? x f32>, index) -> index
```
}];
let arguments = (ins AnyRankedOrUnrankedMemRef:$source,
Index:$index);
let results = (outs Index:$result);
let assemblyFormat = [{
attr-dict $source `,` $index `:` type($source)
}];
let builders = [
OpBuilder<(ins "Value":$source, "int64_t":$index)>,
OpBuilder<(ins "Value":$source, "Value":$index)>
];
let extraClassDeclaration = [{
/// Helper function to get the index as a simple integer if it is constant.
Optional<int64_t> getConstantIndex();
/// Interface method of ShapedDimOpInterface: Return the source memref.
Value getShapedValue() { return getSource(); }
/// Interface method of ShapedDimOpInterface: Return the dimension.
OpFoldResult getDimension() { return getIndex(); }
}];
let hasCanonicalizer = 1;
let hasFolder = 1;
let hasVerifier = 1;
}
//===----------------------------------------------------------------------===//
// DmaStartOp
//===----------------------------------------------------------------------===//
def MemRef_DmaStartOp : MemRef_Op<"dma_start"> {
let summary = "non-blocking DMA operation that starts a transfer";
let description = [{
DmaStartOp starts a non-blocking DMA operation that transfers data from a
source memref to a destination memref. The source and destination memref
need not be of the same dimensionality, but need to have the same elemental
type. The operands include the source and destination memref's each followed
by its indices, size of the data transfer in terms of the number of elements
(of the elemental type of the memref), a tag memref with its indices, and
optionally at the end, a stride and a number_of_elements_per_stride
arguments. The tag location is used by a DmaWaitOp to check for completion.
The indices of the source memref, destination memref, and the tag memref
have the same restrictions as any load/store. The optional stride arguments
should be of 'index' type, and specify a stride for the slower memory space
(memory space with a lower memory space id), transferring chunks of
number_of_elements_per_stride every stride until %num_elements are
transferred. Either both or no stride arguments should be specified. If the
source and destination locations overlap the behavior of this operation is
not defined.
For example, a DmaStartOp operation that transfers 256 elements of a memref
'%src' in memory space 0 at indices [%i, %j] to memref '%dst' in memory
space 1 at indices [%k, %l], would be specified as follows:
```mlir
%num_elements = arith.constant 256
%idx = arith.constant 0 : index
%tag = memref.alloc() : memref<1 x i32, affine_map<(d0) -> (d0)>, 4>
dma_start %src[%i, %j], %dst[%k, %l], %num_elements, %tag[%idx] :
memref<40 x 128 x f32>, affine_map<(d0) -> (d0)>, 0>,
memref<2 x 1024 x f32>, affine_map<(d0) -> (d0)>, 1>,
memref<1 x i32>, affine_map<(d0) -> (d0)>, 2>
```
If %stride and %num_elt_per_stride are specified, the DMA is expected to
transfer %num_elt_per_stride elements every %stride elements apart from
memory space 0 until %num_elements are transferred.
```mlir
dma_start %src[%i, %j], %dst[%k, %l], %num_elements, %tag[%idx], %stride,
%num_elt_per_stride :
```
TODO: add additional operands to allow source and destination striding, and
multiple stride levels.
TODO: Consider replacing src/dst memref indices with view memrefs.
}];
let arguments = (ins Variadic<AnyType>:$operands);
let builders = [
OpBuilder<(ins "Value":$srcMemRef, "ValueRange":$srcIndices,
"Value":$destMemRef, "ValueRange":$destIndices,
"Value":$numElements, "Value":$tagMemRef,
"ValueRange":$tagIndices, CArg<"Value", "{}">:$stride,
CArg<"Value", "{}">:$elementsPerStride)>
];
let extraClassDeclaration = [{
// Returns the source MemRefType for this DMA operation.
Value getSrcMemRef() { return getOperand(0); }
// Returns the rank (number of indices) of the source MemRefType.
unsigned getSrcMemRefRank() {
return getSrcMemRef().getType().cast<MemRefType>().getRank();
}
// Returns the source memref indices for this DMA operation.
operand_range getSrcIndices() {
return {(*this)->operand_begin() + 1,
(*this)->operand_begin() + 1 + getSrcMemRefRank()};
}
// Returns the destination MemRefType for this DMA operations.
Value getDstMemRef() { return getOperand(1 + getSrcMemRefRank()); }
// Returns the rank (number of indices) of the destination MemRefType.
unsigned getDstMemRefRank() {
return getDstMemRef().getType().cast<MemRefType>().getRank();
}
unsigned getSrcMemorySpace() {
return getSrcMemRef().getType().cast<MemRefType>().getMemorySpaceAsInt();
}
unsigned getDstMemorySpace() {
return getDstMemRef().getType().cast<MemRefType>().getMemorySpaceAsInt();
}
// Returns the destination memref indices for this DMA operation.
operand_range getDstIndices() {
return {(*this)->operand_begin() + 1 + getSrcMemRefRank() + 1,
(*this)->operand_begin() + 1 + getSrcMemRefRank() + 1 +
getDstMemRefRank()};
}
// Returns the number of elements being transferred by this DMA operation.
Value getNumElements() {
return getOperand(1 + getSrcMemRefRank() + 1 + getDstMemRefRank());
}
// Returns the Tag MemRef for this DMA operation.
Value getTagMemRef() {
return getOperand(1 + getSrcMemRefRank() + 1 + getDstMemRefRank() + 1);
}
// Returns the rank (number of indices) of the tag MemRefType.
unsigned getTagMemRefRank() {
return getTagMemRef().getType().cast<MemRefType>().getRank();
}
// Returns the tag memref index for this DMA operation.
operand_range getTagIndices() {
unsigned tagIndexStartPos =
1 + getSrcMemRefRank() + 1 + getDstMemRefRank() + 1 + 1;
return {(*this)->operand_begin() + tagIndexStartPos,
(*this)->operand_begin() + tagIndexStartPos + getTagMemRefRank()};
}
/// Returns true if this is a DMA from a faster memory space to a slower
/// one.
bool isDestMemorySpaceFaster() {
return (getSrcMemorySpace() < getDstMemorySpace());
}
/// Returns true if this is a DMA from a slower memory space to a faster
/// one.
bool isSrcMemorySpaceFaster() {
// Assumes that a lower number is for a slower memory space.
return (getDstMemorySpace() < getSrcMemorySpace());
}
/// Given a DMA start operation, returns the operand position of either the
/// source or destination memref depending on the one that is at the higher
/// level of the memory hierarchy. Asserts failure if neither is true.
unsigned getFasterMemPos() {
assert(isSrcMemorySpaceFaster() || isDestMemorySpaceFaster());
return isSrcMemorySpaceFaster() ? 0 : getSrcMemRefRank() + 1;
}
bool isStrided() {
return getNumOperands() != 1 + getSrcMemRefRank() + 1 +
getDstMemRefRank() + 1 + 1 +
getTagMemRefRank();
}
Value getStride() {
if (!isStrided())
return nullptr;
return getOperand(getNumOperands() - 1 - 1);
}
Value getNumElementsPerStride() {
if (!isStrided())
return nullptr;
return getOperand(getNumOperands() - 1);
}
}];
let hasCustomAssemblyFormat = 1;
let hasFolder = 1;
let hasVerifier = 1;
}
//===----------------------------------------------------------------------===//
// DmaWaitOp
//===----------------------------------------------------------------------===//
def MemRef_DmaWaitOp : MemRef_Op<"dma_wait"> {
let summary = "blocking DMA operation that waits for transfer completion";
let description = [{
DmaWaitOp blocks until the completion of a DMA operation associated with the
tag element '%tag[%index]'. %tag is a memref, and %index has to be an index
with the same restrictions as any load/store index. %num_elements is the
number of elements associated with the DMA operation.
Example:
```mlir
dma_start %src[%i, %j], %dst[%k, %l], %num_elements, %tag[%index] :
memref<2048 x f32>, affine_map<(d0) -> (d0)>, 0>,
memref<256 x f32>, affine_map<(d0) -> (d0)>, 1>
memref<1 x i32>, affine_map<(d0) -> (d0)>, 2>
...
...
dma_wait %tag[%index], %num_elements : memref<1 x i32, affine_map<(d0) -> (d0)>, 2>
```
}];
let arguments = (ins AnyMemRef:$tagMemRef,
Variadic<Index>:$tagIndices,
Index:$numElements);
let assemblyFormat = [{
$tagMemRef `[` $tagIndices `]` `,` $numElements attr-dict `:`
type($tagMemRef)
}];
let extraClassDeclaration = [{
/// Returns the rank (number of indices) of the tag memref.
unsigned getTagMemRefRank() {
return getTagMemRef().getType().cast<MemRefType>().getRank();
}
}];
let hasFolder = 1;
let hasVerifier = 1;
}
//===----------------------------------------------------------------------===//
// ExtractAlignedPointerAsIndexOp
//===----------------------------------------------------------------------===//
def MemRef_ExtractAlignedPointerAsIndexOp :
MemRef_Op<"extract_aligned_pointer_as_index", [
DeclareOpInterfaceMethods<OpAsmOpInterface, ["getAsmResultNames"]>,
NoSideEffect,
SameVariadicResultSize]> {
let summary = "Extracts a memref's underlying aligned pointer as an index";
let description = [{
Extracts the underlying aligned pointer as an index.
This operation is useful for lowering to lower-level dialects while still
avoiding the need to define a pointer type in higher-level dialects such as
the memref dialect.
This operation is intended solely as step during lowering, it has no side
effects. A reverse operation that creates a memref from an index interpreted
as a pointer is explicitly discouraged.
Example:
```
%0 = memref.extract_aligned_pointer_as_index %arg : memref<4x4xf32> -> index
%1 = arith.index_cast %0 : index to i64
%2 = llvm.inttoptr %1 : i64 to !llvm.ptr<f32>
call @foo(%2) : (!llvm.ptr<f32>) ->()
```
}];
let arguments = (ins
AnyStridedMemRef:$source
);
let results = (outs Index:$aligned_pointer);
let assemblyFormat = [{
$source `:` type($source) `->` type(results) attr-dict
}];
}
//===----------------------------------------------------------------------===//
// ExtractStridedMetadataOp
//===----------------------------------------------------------------------===//
def MemRef_ExtractStridedMetadataOp : MemRef_Op<"extract_strided_metadata", [
DeclareOpInterfaceMethods<OpAsmOpInterface, ["getAsmResultNames"]>,
NoSideEffect,
SameVariadicResultSize]> {
let summary = "Extracts a buffer base with offset and strides";
let description = [{
Extracts a base buffer, offset and strides. This op allows additional layers
of transformations and foldings to be added as lowering progresses from
higher-level dialect to lower-level dialects such as the LLVM dialect.
The op requires a strided memref source operand. If the source operand is not
a strided memref, then verification fails.
This operation is also useful for completeness to the existing memref.dim op.
While accessing strides, offsets and the base pointer independently is not
available, this is useful for composing with its natural complement op:
`memref.reinterpret_cast`.
Intended Use Cases:
The main use case is to expose the logic for manipulate memref metadata at a
higher level than the LLVM dialect.
This makes lowering more progressive and brings the following benefits:
- not all users of MLIR want to lower to LLVM and the information to e.g.
lower to library calls---like libxsmm---or to SPIR-V was not available.
- foldings and canonicalizations can happen at a higher level in MLIR:
before this op existed, lowering to LLVM would create large amounts of
LLVMIR. Even when LLVM does a good job at folding the low-level IR from
a performance perspective, it is unnecessarily opaque and inefficient to
send unkempt IR to LLVM.
Example:
```mlir
%base, %offset, %sizes:2, %strides:2 =
memref.extract_strided_metadata %memref :
memref<10x?xf32>, index, index, index, index, index
// After folding, the type of %m2 can be memref<10x?xf32> and further
// folded to %memref.
%m2 = memref.reinterpret_cast %base to
offset: [%offset],
sizes: [%sizes#0, %sizes#1],
strides: [%strides#0, %strides#1]
: memref<f32> to memref<?x?xf32, offset: ?, strides: [?, ?]>
```
}];
let arguments = (ins
AnyStridedMemRef:$source
);
let results = (outs
AnyStridedMemRefOfRank<0>:$base_buffer,
Index:$offset,
Variadic<Index>:$sizes,
Variadic<Index>:$strides
);
let assemblyFormat = [{
$source `:` type($source) `->` type(results) attr-dict
}];
}
//===----------------------------------------------------------------------===//
// GenericAtomicRMWOp
//===----------------------------------------------------------------------===//
def GenericAtomicRMWOp : MemRef_Op<"generic_atomic_rmw", [
SingleBlockImplicitTerminator<"AtomicYieldOp">,
TypesMatchWith<"result type matches element type of memref",
"memref", "result",
"$_self.cast<MemRefType>().getElementType()">
]> {
let summary = "atomic read-modify-write operation with a region";
let description = [{
The `memref.generic_atomic_rmw` operation provides a way to perform a
read-modify-write sequence that is free from data races. The memref operand
represents the buffer that the read and write will be performed against, as
accessed by the specified indices. The arity of the indices is the rank of
the memref. The result represents the latest value that was stored. The
region contains the code for the modification itself. The entry block has
a single argument that represents the value stored in `memref[indices]`
before the write is performed. No side-effecting ops are allowed in the
body of `GenericAtomicRMWOp`.
Example:
```mlir
%x = memref.generic_atomic_rmw %I[%i] : memref<10xf32> {
^bb0(%current_value : f32):
%c1 = arith.constant 1.0 : f32
%inc = arith.addf %c1, %current_value : f32
memref.atomic_yield %inc : f32
}
```
}];
let arguments = (ins
MemRefOf<[AnySignlessInteger, AnyFloat]>:$memref,
Variadic<Index>:$indices);
let results = (outs
AnyTypeOf<[AnySignlessInteger, AnyFloat]>:$result);
let regions = (region AnyRegion:$atomic_body);
let skipDefaultBuilders = 1;
let builders = [OpBuilder<(ins "Value":$memref, "ValueRange":$ivs)>];
let extraClassDeclaration = [{
// TODO: remove post migrating callers.
Region &body() { return getRegion(); }
// The value stored in memref[ivs].
Value getCurrentValue() {
return getRegion().getArgument(0);
}
MemRefType getMemRefType() {
return getMemref().getType().cast<MemRefType>();
}
}];
let hasCustomAssemblyFormat = 1;
let hasVerifier = 1;
}
def AtomicYieldOp : MemRef_Op<"atomic_yield", [
HasParent<"GenericAtomicRMWOp">,
NoSideEffect,
Terminator
]> {
let summary = "yield operation for GenericAtomicRMWOp";
let description = [{
"memref.atomic_yield" yields an SSA value from a
GenericAtomicRMWOp region.
}];
let arguments = (ins AnyType:$result);
let assemblyFormat = "$result attr-dict `:` type($result)";
let hasVerifier = 1;
}
//===----------------------------------------------------------------------===//
// GetGlobalOp
//===----------------------------------------------------------------------===//
def MemRef_GetGlobalOp : MemRef_Op<"get_global",
[NoSideEffect, DeclareOpInterfaceMethods<SymbolUserOpInterface>]> {
let summary = "get the memref pointing to a global variable";
let description = [{
The `memref.get_global` operation retrieves the memref pointing to a
named global variable. If the global variable is marked constant, writing