-
Notifications
You must be signed in to change notification settings - Fork 183
Expand file tree
/
Copy pathAIEObjectFifoStatefulTransform.cpp
More file actions
2604 lines (2380 loc) · 107 KB
/
AIEObjectFifoStatefulTransform.cpp
File metadata and controls
2604 lines (2380 loc) · 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- AIEObjectFifoStatefulTransform.cpp ----------------------*- MLIR -*-===//
//
// This file is licensed 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
//
// (c) Copyright 2021 Xilinx Inc.
//
// Date: October 18th 2021
//
//===----------------------------------------------------------------------===//
#include "aie/Dialect/AIE/IR/AIEDialect.h"
#include "aie/Dialect/AIE/Transforms/AIEPasses.h"
#include "mlir/Analysis/TopologicalSortUtils.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/SCF/IR/SCF.h"
#include "mlir/Dialect/SCF/Utils/Utils.h"
#include "mlir/IR/Attributes.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/DialectConversion.h"
#include "mlir/IR/Operation.h"
#include "mlir/Interfaces/DataLayoutInterfaces.h"
#include <numeric>
#include <set>
#include <iostream>
namespace xilinx::AIE {
#define GEN_PASS_DEF_AIEOBJECTFIFOSTATEFULTRANSFORM
#include "aie/Dialect/AIE/Transforms/AIEPasses.h.inc"
} // namespace xilinx::AIE
using namespace mlir;
using namespace xilinx;
using namespace xilinx::AIE;
#define DEBUG_TYPE "aie-objectFifo-stateful-transform"
#define LOOP_VAR_DEPENDENCY (-2)
//===----------------------------------------------------------------------===//
// Lock Analysis
//===----------------------------------------------------------------------===//
class LockAnalysis {
DenseMap<std::pair<Value, int>, int> locksPerTile;
public:
LockAnalysis(DeviceOp &device) {
// go over the locks created for each tile and update the index in
// locksPerTile
device.walk([&](LockOp lockOp) {
auto tile = lockOp.getTile();
auto lockID = lockOp.getLockIDValue();
locksPerTile[{tile, lockID}] = 1;
});
}
/// Given a tile, returns next usable lockID for that tile.
int getLockID(TileOp &tileOp) {
const auto &targetModel = getTargetModel(tileOp);
for (unsigned i = 0;
i < targetModel.getNumLocks(tileOp.getCol(), tileOp.getRow()); i++)
if (int usageCnt = locksPerTile[{tileOp, i}]; usageCnt == 0) {
locksPerTile[{tileOp, i}] = 1;
return i;
}
return -1;
}
};
//===----------------------------------------------------------------------===//
// DMA Channel Analysis
//===----------------------------------------------------------------------===//
class DMAChannelAnalysis {
DenseMap<std::tuple<Value, DMAChannelDir, int>, int> channelsPerTile;
DenseMap<std::tuple<Value, DMAChannelDir, int>, int> aieStreamsPerTile;
public:
DMAChannelAnalysis(DeviceOp &device) {
// go over the channels used for each tile and update channel map
for (auto memOp : device.getOps<MemOp>()) {
Region &r = memOp.getBody();
for (auto &bl : r.getBlocks()) {
for (auto op : bl.getOps<DMAStartOp>()) {
channelsPerTile[{memOp.getTile(), op.getChannelDir(),
op.getChannelIndex()}] = 1;
}
}
}
for (auto memOp : device.getOps<MemTileDMAOp>()) {
Region &r = memOp.getBody();
for (auto &bl : r.getBlocks()) {
for (auto op : bl.getOps<DMAStartOp>()) {
channelsPerTile[{memOp.getTile(), op.getChannelDir(),
op.getChannelIndex()}] = 1;
}
}
}
for (auto memOp : device.getOps<ShimDMAOp>()) {
Region &r = memOp.getBody();
for (auto &bl : r.getBlocks()) {
for (auto op : bl.getOps<DMAStartOp>()) {
channelsPerTile[{memOp.getTile(), op.getChannelDir(),
op.getChannelIndex()}] = 1;
}
}
}
for (auto flowOp : device.getOps<FlowOp>()) {
if (flowOp.getSourceBundle() == WireBundle::Core)
aieStreamsPerTile[{flowOp.getSource(), DMAChannelDir::MM2S,
flowOp.getSourceChannel()}] = 1;
if (flowOp.getDestBundle() == WireBundle::Core)
aieStreamsPerTile[{flowOp.getDest(), DMAChannelDir::S2MM,
flowOp.getDestChannel()}] = 1;
}
}
/// Given a tile and DMAChannelDir, returns next usable channel index for
/// that tile.
int getDMAChannelIndex(TileOp tileOp, DMAChannelDir dir,
bool requiresAdjacentTileAccessChannels) {
int maxChannelNum = 0;
if (dir == DMAChannelDir::MM2S)
maxChannelNum = tileOp.getNumSourceConnections(WireBundle::DMA);
else
maxChannelNum = tileOp.getNumDestConnections(WireBundle::DMA);
const auto &targetModel = getTargetModel(tileOp);
int maxChannelNumForAdjacentTile =
targetModel.getMaxChannelNumForAdjacentMemTile(tileOp.getCol(),
tileOp.getRow());
// if requires adjacent tile access channels, only allocate on channel 0-3,
// and if cannot, return 0
if (requiresAdjacentTileAccessChannels) {
maxChannelNum = std::min(maxChannelNum, maxChannelNumForAdjacentTile);
}
for (int i = 0; i < maxChannelNum; i++) {
if (int usageCnt = channelsPerTile[{tileOp.getResult(), dir, i}];
usageCnt == 0) {
channelsPerTile[{tileOp.getResult(), dir, i}] = 1;
return i;
}
}
return -1;
}
/// Given a tile and DMAChannel, adds entry to aieStreamsPerTile or
/// throws an error if the stream is already used.
void checkAIEStreamIndex(TileOp tileOp, DMAChannel chan) {
if (aieStreamsPerTile.find({tileOp.getResult(), chan.direction,
chan.channel}) == aieStreamsPerTile.end()) {
aieStreamsPerTile[{tileOp.getResult(), chan.direction, chan.channel}] = 1;
} else {
if (chan.direction == DMAChannelDir::MM2S)
tileOp.emitOpError("number of output Core channels exceeded!");
else
tileOp.emitOpError("number of input Core channels exceeded!");
}
}
};
//===----------------------------------------------------------------------===//
// Create objectFifos Pass
//===----------------------------------------------------------------------===//
/// Struct to hold per-device state for the objectFifo transformation.
/// This is passed to helper functions to avoid member variable pollution
/// between different device operations.
struct ObjectFifoState {
DenseMap<ObjectFifoCreateOp, std::vector<BufferOp>>
buffersPerFifo; // maps each objFifo to its corresponding buffer
DenseMap<ObjectFifoCreateOp, std::vector<ExternalBufferOp>>
externalBuffersPerFifo; // maps each objFifo to its corresponding
// external buffers
DenseMap<ObjectFifoCreateOp, std::vector<LockOp>>
locksPerFifo; // maps each objFifo to its corresponding locks
std::vector<std::pair<ObjectFifoCreateOp, std::vector<ObjectFifoCreateOp>>>
splitFifos; // maps each objFifo between non-adjacent tiles to its
// corresponding consumer objectFifos
DenseMap<ObjectFifoLinkOp, ObjectFifoCreateOp>
objFifoLinks; // maps each ObjectFifoLinkOp to objFifo whose elements
// have been created and should be used
std::vector<ObjectFifoCreateOp>
splitBecauseLink; // objfifos which have been split because they are
// part of a Link, not because they didn't have a shared
// memory module
};
struct AIEObjectFifoStatefulTransformPass
: xilinx::AIE::impl::AIEObjectFifoStatefulTransformBase<
AIEObjectFifoStatefulTransformPass> {
/// Function that returns true if two tiles in the AIE array share a memory
/// module. share_direction is equal to:
/// * 2 if the memory modules on both tiles can be shared,
/// * -1 if the shared memory module is that of the first input tile,
/// * 1 if it is that of the second input tile,
/// * 0 is no memory module is shared.
bool isSharedMemory(TileOp a, TileOp b, int *share_direction) {
const auto &targetModel = getTargetModel(a.getOperation());
if ((a.isShimTile() && !b.isShimTile()) ||
(!a.isShimTile() && b.isShimTile())) {
*share_direction = 0;
return false;
}
if ((targetModel.isMemTile(a.getCol(), a.getRow()) &&
!targetModel.isMemTile(b.getCol(), b.getRow())) ||
(!targetModel.isMemTile(a.getCol(), a.getRow()) &&
targetModel.isMemTile(b.getCol(), b.getRow()))) {
*share_direction = 0;
return false;
}
bool rightShared = targetModel.isLegalMemAffinity(
a.colIndex(), a.rowIndex(), b.colIndex(), b.rowIndex());
bool leftShared = targetModel.isLegalMemAffinity(
b.colIndex(), b.rowIndex(), a.colIndex(), a.rowIndex());
if (leftShared && rightShared)
*share_direction = 2;
else if (leftShared)
*share_direction = -1;
else if (rightShared)
*share_direction = 1;
else
*share_direction = 0;
return leftShared || rightShared;
}
/// Function to retrieve ObjectFifoAllocateOp of ObjectFifoCreateOp,
/// if it exists.
std::optional<ObjectFifoAllocateOp>
getOptionalAllocateOp(ObjectFifoCreateOp op) {
ObjectFifoAllocateOp allocOp;
auto device = op->getParentOfType<DeviceOp>();
bool foundAlloc = false;
for (ObjectFifoAllocateOp alloc : device.getOps<ObjectFifoAllocateOp>()) {
if (alloc.getObjectFifo() == op) {
if (foundAlloc)
op.emitOpError("has more than one allocate operation");
allocOp = alloc;
foundAlloc = true;
}
}
if (foundAlloc)
return {allocOp};
return {};
}
// Return true if the objectFifo created by createOp requires a DMA to be set
// up. This is the case if the tiles are not adjacent (no shared memory), if
// the objectFifo broadcasts to multiple tiles, if one of the consumers or
// the producer wants to use the multi-dimensional address generation
// features of the DMA, if the objectFifo is part of a LinkOp, or if the
// via_DMA or repeatCount attributes of the objectFifo are set.
bool requiresDMAs(ObjectFifoCreateOp createOp, int &share_direction,
ObjectFifoState &state) {
bool hasSharedMemory = false;
bool atLeastOneConsumerWantsTransform = false;
bool isUsedInLinkOp = false;
if (createOp.getVia_DMA())
return true;
if (createOp.getRepeatCount().has_value())
return true;
if (createOp.getAieStream())
return true;
if (createOp.getConsumerTiles().size() == 1 &&
createOp.getDimensionsToStream().empty()) {
// Test for shared memory
for (auto consumerTile : createOp.getConsumerTiles()) {
if (auto consumerTileOp =
dyn_cast<TileOp>(consumerTile.getDefiningOp())) {
if (std::count(state.splitBecauseLink.begin(),
state.splitBecauseLink.end(), createOp))
hasSharedMemory =
isSharedMemory(createOp.getProducerTileOp(),
createOp.getProducerTileOp(), &share_direction);
else
hasSharedMemory = isSharedMemory(createOp.getProducerTileOp(),
consumerTileOp, &share_direction);
}
}
}
// Only test for use of data layout transformations if we are in the shared
// memory case; otherwise, we will return `true` in any case.
if (hasSharedMemory) {
// Even if just one of the consumers in the list of consumers wants to
// perform a memory transform, we need to use DMAs.
for (BDDimLayoutArrayAttr dims :
createOp.getDimensionsFromStreamPerConsumer())
if (!dims.empty()) {
atLeastOneConsumerWantsTransform = true;
break;
}
}
// Check if the objectfifo operation can use shared memory for linking. If
// the link operation is a distribute or a join operation, or if the link
// has different memref types, DMAs are required even if shared memory is
// available and the objectfifo should be split. Otherwise also check if the
// via_shared_memory attribute of the objectfifo operation is set and try to
// apply it.
if (hasSharedMemory) {
if (auto linkOp = getOptionalLinkOp(createOp)) {
isUsedInLinkOp = true;
if (!linkOp->isDistribute() && !linkOp->isJoin()) {
auto fifoInType = llvm::cast<AIEObjectFifoType>(
linkOp->getInputObjectFifos()[0].getElemType());
auto producerType =
llvm::cast<MemRefType>(fifoInType.getElementType());
auto fifoOutType = llvm::cast<AIEObjectFifoType>(
linkOp->getOutputObjectFifos()[0].getElemType());
auto consumerType =
llvm::cast<MemRefType>(fifoOutType.getElementType());
if (consumerType != producerType) {
// TODO: Support for different memref types through shared
// memory without DMAs
state.splitBecauseLink.push_back(createOp);
}
std::optional<ObjectFifoAllocateOp> opAlloc =
getOptionalAllocateOp(createOp);
if (opAlloc.has_value()) {
TileOp delegate = opAlloc->getDelegateTileOp();
int prodShareDir;
int consShareDir;
auto consumerTileOp = dyn_cast<TileOp>(
createOp.getConsumerTiles()[0].getDefiningOp());
isSharedMemory(delegate, createOp.getProducerTileOp(),
&prodShareDir);
isSharedMemory(delegate, consumerTileOp, &consShareDir);
if ((prodShareDir == -1 || prodShareDir == 2) &&
(consShareDir == -1 || consShareDir == 2))
isUsedInLinkOp = false;
else
state.splitBecauseLink.push_back(createOp);
}
} else {
state.splitBecauseLink.push_back(createOp);
}
}
}
return !hasSharedMemory || atLeastOneConsumerWantsTransform ||
isUsedInLinkOp;
}
/// Function to retrieve ObjectFifoLinkOp of ObjectFifoCreateOp,
/// if it belongs to one.
std::optional<ObjectFifoLinkOp> getOptionalLinkOp(ObjectFifoCreateOp op) {
auto device = op->getParentOfType<DeviceOp>();
for (ObjectFifoLinkOp linkOp : device.getOps<ObjectFifoLinkOp>()) {
for (ObjectFifoCreateOp in : linkOp.getInputObjectFifos())
if (in == op)
return {linkOp};
for (ObjectFifoCreateOp out : linkOp.getOutputObjectFifos())
if (out == op)
return {linkOp};
}
return {};
}
ObjectFifoCreateOp
createObjectFifo(OpBuilder &builder, AIEObjectFifoType datatype,
std::string name, Value prodTile, Value consTile,
Attribute depth, BDDimLayoutArrayAttr dimensionsToStream,
BDDimLayoutArrayArrayAttr dimensionsFromStreamPerConsumer) {
auto ofName = builder.getStringAttr(name);
auto fifo = ObjectFifoCreateOp::create(
builder, builder.getUnknownLoc(), ofName, prodTile, consTile, depth,
datatype, dimensionsToStream, dimensionsFromStreamPerConsumer);
return fifo;
}
/// Function used to create objectFifo locks based on target architecture.
/// Called by createObjectFifoElements().
std::vector<LockOp>
createObjectFifoLocks(OpBuilder &builder, LockAnalysis &lockAnalysis,
ObjectFifoCreateOp op, int numElem,
int joinDistribFactor, TileOp creation_tile,
int repeatCount, ObjectFifoState &state) {
std::vector<LockOp> locks;
if (op.getDisableSynchronization())
return locks;
auto dev = op->getParentOfType<DeviceOp>();
auto &target = dev.getTargetModel();
// if shimTile external buffers are collected from input code
// create as many locks as there are external buffers
if (creation_tile.isShimTile()) {
numElem = 0;
if (!state.externalBuffersPerFifo[op].empty())
numElem = state.externalBuffersPerFifo[op].size();
}
if (target.getTargetArch() == AIEArch::AIE1) {
for (int i = 0; i < numElem; i++) {
// create corresponding aie1 locks
int initValue = op.getInitValues().has_value() ? 1 : 0;
int lockID = lockAnalysis.getLockID(creation_tile);
assert(lockID >= 0 && "No more locks to allocate!");
auto lock = LockOp::create(builder, builder.getUnknownLoc(),
creation_tile, lockID, initValue);
lock.getOperation()->setAttr(SymbolTable::getSymbolAttrName(),
builder.getStringAttr(op.name().str() +
"_lock_" +
std::to_string(i)));
locks.push_back(lock);
}
} else {
// create corresponding aie2 locks
for (int i = 0; i < joinDistribFactor; i++) {
auto initValues = op.getInitValues().has_value()
? op.getInitValues().value().size()
: 0;
int prodLockID = lockAnalysis.getLockID(creation_tile);
assert(prodLockID >= 0 && "No more locks to allocate!");
int prodLockValue = (numElem - initValues) * repeatCount;
auto prodLock =
LockOp::create(builder, builder.getUnknownLoc(), creation_tile,
prodLockID, prodLockValue);
prodLock.getOperation()->setAttr(
SymbolTable::getSymbolAttrName(),
builder.getStringAttr(op.name().str() + "_prod_lock_" +
std::to_string(i)));
locks.push_back(prodLock);
int consLockID = lockAnalysis.getLockID(creation_tile);
assert(consLockID >= 0 && "No more locks to allocate!");
int consLockValue = initValues * repeatCount;
auto consLock =
LockOp::create(builder, builder.getUnknownLoc(), creation_tile,
consLockID, consLockValue);
consLock.getOperation()->setAttr(
SymbolTable::getSymbolAttrName(),
builder.getStringAttr(op.name().str() + "_cons_lock_" +
std::to_string(i)));
locks.push_back(consLock);
}
}
return locks;
}
/// Function to calculate total memory usage on a specific tile
/// based on all buffers allocated to that tile from buffersPerFifo map
int calculateCurrentUsedMemory(
TileOp targetTile,
DenseMap<ObjectFifoCreateOp, std::vector<BufferOp>> &buffersPerFifo,
std::vector<BufferOp> &buffers) {
int totalUsedMemory = 0;
// Iterate through all ObjectFifos and their buffers
for (auto &[fifoOp, bufferList] : buffersPerFifo) {
for (auto &buffer : bufferList) {
// Check if this buffer is allocated on the target tile
if (buffer.getTile() == targetTile.getResult()) {
auto bufferSizeBytes = buffer.getAllocationSize();
totalUsedMemory += bufferSizeBytes;
}
}
}
// Also count buffers that are not in buffersPerFifo
for (auto &buffer : buffers) {
// Check if this buffer is allocated on the target tile
if (buffer.getTile() == targetTile.getResult()) {
auto bufferSizeBytes = buffer.getAllocationSize();
totalUsedMemory += bufferSizeBytes;
}
}
return totalUsedMemory;
}
/// Function to analyze cross-tile buffer allocations in splitFifos
/// Returns a simple map of (ObjectFifoCreateOp, bool) indicating cross-tile
/// issues
std::map<ObjectFifoCreateOp, bool>
analyzeCrossTileFIFOBuffers(ObjectFifoState &state) {
std::map<ObjectFifoCreateOp, bool> crossTileMap;
for (size_t i = 0; i < state.splitFifos.size(); i++) {
auto &[producerFifo, consumerFifos] = state.splitFifos[i];
// Analyze producer buffers
bool producerHasCrossTile = false;
ObjectFifoCreateOp target = producerFifo;
auto linkOp = getOptionalLinkOp(producerFifo);
if (linkOp &&
state.objFifoLinks.find(*linkOp) != state.objFifoLinks.end()) {
target = state.objFifoLinks[*linkOp]; // Use the linked target FIFO
}
if (state.buffersPerFifo.find(target) != state.buffersPerFifo.end()) {
// For each FIFO (producer and consumer):
auto &producerBuffers = state.buffersPerFifo[target];
TileOp expectedTile = target.getProducerTileOp();
for (auto &buffer : producerBuffers) {
TileOp bufferTile = buffer.getTile().getDefiningOp<TileOp>();
if (bufferTile != expectedTile) {
producerHasCrossTile = true;
break;
}
}
}
crossTileMap[producerFifo] = producerHasCrossTile;
// Analyze consumer buffers
for (auto &consumerFifo : consumerFifos) {
bool consumerHasCrossTile = false;
ObjectFifoCreateOp target = consumerFifo;
auto linkOp = getOptionalLinkOp(consumerFifo);
if (linkOp &&
state.objFifoLinks.find(*linkOp) != state.objFifoLinks.end()) {
target = state.objFifoLinks[*linkOp]; // Use the linked target FIFO
}
if (state.buffersPerFifo.find(target) != state.buffersPerFifo.end()) {
// For each FIFO (producer and consumer):
auto &consumerBuffers = state.buffersPerFifo[target];
TileOp expectedTile = target.getProducerTileOp();
for (auto &buffer : consumerBuffers) {
TileOp bufferTile = buffer.getTile().getDefiningOp<TileOp>();
if (bufferTile != expectedTile) {
consumerHasCrossTile = true;
break;
}
}
}
crossTileMap[consumerFifo] = consumerHasCrossTile;
}
}
return crossTileMap;
}
/// Helper function to find a tile at specific coordinates.
/// If a tile is not found, it creates a new one and returns it.
/// hostTile is the original tile from which we are searching for neighbors.
/// we create the new tile below the hostTile
TileOp findOrCreateTile(OpBuilder &builder, DeviceOp &dev, TileOp hostTile,
int col, int row) {
// First, try to find an existing tile
for (auto tile : dev.getOps<TileOp>()) {
if (tile.getCol() == col && tile.getRow() == row) {
return tile;
}
}
// If not found, create a new one.
OpBuilder::InsertionGuard g(builder);
auto savedInsertionPoint = builder.saveInsertionPoint();
// Find the last buffer operation after the host tile
Operation *insertAfter = hostTile.getOperation();
Operation *nextOp = insertAfter->getNextNode();
while (nextOp && isa<BufferOp>(nextOp)) {
insertAfter = nextOp;
nextOp = nextOp->getNextNode();
}
builder.setInsertionPointAfter(insertAfter);
auto newTile = TileOp::create(builder, builder.getUnknownLoc(), col, row);
builder.restoreInsertionPoint(savedInsertionPoint);
return newTile;
}
/// Function used to create objectFifo elements and their locks.
/// It maps the input objectFifo to associated buffers and locks.
void createObjectFifoElements(OpBuilder &builder, LockAnalysis &lockAnalysis,
ObjectFifoCreateOp op, int share_direction,
ObjectFifoState &state) {
if (!op.size())
return;
if (op.getAieStream())
return;
std::vector<BufferOp> buffers;
auto fifo = llvm::cast<AIEObjectFifoType>(op.getElemType());
auto elemType = llvm::cast<MemRefType>(fifo.getElementType());
int numElem = op.size();
int of_elem_index = 0; // used to give objectFifo elements a symbolic name
// if this objectFifo is linked to another, check if the other's elements
// have already been created: if none of the output objectfifos of the link
// have initValues, then the elements that are created are those of the
// objFifo with elements of bigger size
bool linked = false;
auto linkOp = getOptionalLinkOp(op);
if (linkOp) {
auto fifoIn = linkOp->getInputObjectFifos()[0];
auto fifoOut = linkOp->getOutputObjectFifos()[0];
linked = true;
if (state.objFifoLinks.find(*linkOp) != state.objFifoLinks.end())
return; // elements have already been created
if (linkOp->isJoin()) {
// if join, fifoOut has bigger size
if (op.name() != fifoOut.name())
return;
} else if (linkOp->isDistribute()) {
// if distribute, fifoIn has bigger size
if (op.name() != fifoIn.name())
return;
} else {
// check if output objectfifo has initValues
if (fifoOut.getInitValues().has_value()) {
if (fifoOut.name() != op.name())
return;
} else {
// check which objectfifo of the link has bigger size
auto fifoInType = llvm::cast<AIEObjectFifoType>(fifoIn.getElemType());
auto elemInType = llvm::cast<MemRefType>(fifoInType.getElementType());
int inSize = elemInType.getNumElements();
auto fifoOutType =
llvm::cast<AIEObjectFifoType>(fifoOut.getElemType());
auto elemOutType =
llvm::cast<MemRefType>(fifoOutType.getElementType());
if (int outSize = elemOutType.getNumElements(); inSize >= outSize) {
if (op.name() != fifoIn.name())
return;
} else {
// When output has padDimensions, MemTile buffer should use
// input (smaller) size — padding is applied on-the-fly by DMA
bool outHasPadding = fifoOut.getPadDimensions().has_value();
if (outHasPadding) {
if (op.name() != fifoIn.name())
return;
} else {
if (fifoOut.name() != op.name())
return;
}
}
}
}
}
TileOp creation_tile;
auto consumerTileOp =
dyn_cast<TileOp>(op.getConsumerTiles()[0].getDefiningOp());
if (share_direction != 1)
creation_tile = op.getProducerTileOp();
else
creation_tile = consumerTileOp;
std::optional<ObjectFifoAllocateOp> opAlloc = getOptionalAllocateOp(op);
if (opAlloc.has_value()) {
TileOp delegate = opAlloc->getDelegateTileOp();
int prodShareDir;
int consShareDir;
isSharedMemory(delegate, op.getProducerTileOp(), &prodShareDir);
isSharedMemory(delegate, consumerTileOp, &consShareDir);
if ((prodShareDir == -1 || prodShareDir == 2) &&
(consShareDir == -1 || consShareDir == 2))
creation_tile = delegate;
else
opAlloc->emitOpError("objectfifo has no shared memory access to "
"delegate tile's memory module");
}
// Reset opbuilder location to after the last tile declaration
Operation *t = nullptr;
auto dev = op->getParentOfType<DeviceOp>();
for (auto tile_op : dev.getBody()->getOps<TileOp>()) {
t = tile_op.getOperation();
}
builder.setInsertionPointAfter(t);
for (int i = 0; i < numElem; i++) {
mlir::ElementsAttr initValues = nullptr;
if (!creation_tile.isShimTile()) {
if (op.getInitValues().has_value()) {
initValues =
llvm::cast<mlir::ElementsAttr>(op.getInitValues().value()[i]);
}
auto elementType = elemType.getElementType();
DataLayout dataLayout = DataLayout::closest(op.getOperation());
int64_t elementBitWidth = dataLayout.getTypeSizeInBits(elementType);
auto totalSizeBytes = elemType.getNumElements() * elementBitWidth / 8;
auto &targetModel = dev.getTargetModel();
int maxDataMemorySize = 0;
if (creation_tile.isMemTile())
maxDataMemorySize =
targetModel.getMemTileSize(); // getMemTileSize returns in Bytes
else
maxDataMemorySize =
targetModel
.getLocalMemorySize(); // getLocalMemorySize returns in Bytes
// also need to count the buffers that are not in buffersPerFifo
int currentUsedMemory = calculateCurrentUsedMemory(
creation_tile, state.buffersPerFifo, buffers);
// Check if current tile can hold the new buffer or not
TileOp current_buf_allocation_tile =
creation_tile; // used to keep track of the tile where the buffer is
// allocated
if (creation_tile.isMemTile()) {
if (static_cast<int>(currentUsedMemory + totalSizeBytes) >
maxDataMemorySize) {
// if not, check if the neighbour can hold the new buffer or not
// Find neighbor tiles with shared memory
std::vector<TileOp> neighborTiles;
int currentCol = creation_tile.getCol();
int currentRow = creation_tile.getRow();
// Check tile to the left
if (currentCol > 0) {
TileOp leftTile = findOrCreateTile(builder, dev, creation_tile,
currentCol - 1, currentRow);
int share_direction = 0;
if (isSharedMemory(creation_tile, leftTile, &share_direction) &&
(share_direction == 1 || share_direction == 2)) {
neighborTiles.push_back(leftTile);
}
}
// Check tile to the right
if (currentCol < (targetModel.columns() - 1)) {
TileOp rightTile = findOrCreateTile(builder, dev, creation_tile,
currentCol + 1, currentRow);
int share_direction = 0;
if (isSharedMemory(creation_tile, rightTile, &share_direction) &&
(share_direction == 1 || share_direction == 2)) {
neighborTiles.push_back(rightTile);
}
}
// try to allocate on neighbor tiles
if (!neighborTiles.empty()) {
for (auto &tile : neighborTiles) {
// Try to allocate on this neighbor tile
int neighborUsedMemory = calculateCurrentUsedMemory(
tile, state.buffersPerFifo, buffers);
if (static_cast<int>(neighborUsedMemory + totalSizeBytes) <=
maxDataMemorySize) {
// Allocate buffer on neighbor tile, change creation_tile to
// be this neighbour tile
current_buf_allocation_tile = tile;
break;
}
}
}
}
}
auto buff = BufferOp::create(
builder, builder.getUnknownLoc(), elemType,
current_buf_allocation_tile,
builder.getStringAttr(op.name().str() + "_buff_" +
std::to_string(of_elem_index)),
/*address*/ nullptr, initValues,
/*mem_bank*/ nullptr);
buffers.push_back(buff);
}
of_elem_index++;
}
int repeatCount = 1;
int joinDistribFactor = 1;
if (op.getRepeatCount().has_value())
repeatCount = op.getRepeatCount().value();
if (linked) {
if (linkOp->getRepeatCount().has_value())
repeatCount = linkOp->getRepeatCount().value();
if (linkOp->isDistribute())
joinDistribFactor *= linkOp->getFifoOuts().size();
else if (linkOp->isJoin())
joinDistribFactor *= linkOp->getFifoIns().size();
state.objFifoLinks[*linkOp] = op;
}
std::vector<LockOp> locks = createObjectFifoLocks(
builder, lockAnalysis, op, numElem, joinDistribFactor, creation_tile,
repeatCount, state);
state.buffersPerFifo[op] = buffers;
state.locksPerFifo[op] = locks;
}
/// Function that returns a pointer to the block of a Region
/// that contains the AIEEndOp.
Block *findEndOpBlock(Region &r) {
Block *endBlock = nullptr;
for (auto &bl : r.getBlocks())
if (!bl.getOps<EndOp>().empty())
endBlock = &bl;
return endBlock;
}
/// Function used to create a Bd block.
///
/// Returns the newly created DMABDOp so the caller can decorate it with
/// dataflow-source-specific discardable attributes (e.g. the
/// SparseFifo (de)compression bit propagated from the originating
template <typename MyOp>
DMABDOp createBd(OpBuilder &builder, LockOp acqLock, int acqMode,
LockAction acqLockAction, LockOp relLock, int relMode,
MyOp buff, int offset, int len, Block *succ,
BDDimLayoutArrayAttr dims,
BDPadLayoutArrayAttr padDimensions,
std::optional<PacketInfoAttr> bdPacket) {
if (acqLock)
UseLockOp::create(builder, builder.getUnknownLoc(), acqLock,
acqLockAction, acqMode);
if (bdPacket) {
DMABDPACKETOp::create(builder, builder.getUnknownLoc(),
bdPacket->getPktType(), bdPacket->getPktId());
}
DMABDOp bdOp = [&]() {
if (!dims.getValue().empty() && padDimensions) {
return DMABDOp::create(builder, builder.getUnknownLoc(), buff, offset,
len, dims, padDimensions);
}
if (!dims.getValue().empty()) {
return DMABDOp::create(builder, builder.getUnknownLoc(), buff, offset,
len, dims);
}
return DMABDOp::create(builder, builder.getUnknownLoc(), buff, offset,
len);
}();
if (acqLock)
UseLockOp::create(builder, builder.getUnknownLoc(), relLock,
LockAction::Release, relMode);
NextBDOp::create(builder, builder.getUnknownLoc(), succ);
return bdOp;
}
/// Function used to create a Bd block.
/// If lockMode is 0 we create a consumerDMA (i.e. on producer tile) else a
/// producerDMA (i.e. on consumer tile).
template <typename MyOp>
void createBdBlock(OpBuilder &builder, ObjectFifoCreateOp op, int lockMode,
int acqNum, int relNum, MyOp buff, int offset, int len,
DMAChannelDir channelDir, size_t lockIndex, Block *succ,
BDDimLayoutArrayAttr dims,
BDPadLayoutArrayAttr padDimensions,
std::optional<PacketInfoAttr> bdPacket,
ObjectFifoState &state, bool distribOrJoin = false) {
LockOp acqLock;
LockOp relLock;
int acqMode = 1;
int relMode = 1;
auto acqLockAction = LockAction::Acquire;
if (state.locksPerFifo[op].size() > 0) {
auto dev = op->getParentOfType<DeviceOp>();
if (auto &target = dev.getTargetModel();
target.getTargetArch() == AIEArch::AIE1) {
acqMode = lockMode == 0 ? 1 : 0;
relMode = lockMode == 0 ? 0 : 1;
acqLock = state.locksPerFifo[op][lockIndex];
relLock = state.locksPerFifo[op][lockIndex];
} else {
acqMode = acqNum;
relMode = relNum;
acqLockAction = LockAction::AcquireGreaterEqual;
int prodLockIndex = 0;
int consLockIndex = 1;
if (distribOrJoin) {
prodLockIndex = lockIndex * 2;
consLockIndex = lockIndex * 2 + 1;
}
acqLock = channelDir == DMAChannelDir::S2MM
? state.locksPerFifo[op][prodLockIndex]
: state.locksPerFifo[op][consLockIndex];
relLock = channelDir == DMAChannelDir::S2MM
? state.locksPerFifo[op][consLockIndex]
: state.locksPerFifo[op][prodLockIndex];
}
}
DMABDOp bdOp = createBd(builder, acqLock, acqMode, acqLockAction, relLock,
relMode, buff, offset, len, succ, dims,
padDimensions, bdPacket);
// originating ObjectFifoCreateOp onto each DMABDOp we just created so
// downstream BD-emit (AIEDMATasksToNPU -> AIEDmaToNpu) can flip the
// per-channel ``Enable_Compression`` bit on the AIE2/AIE2P tile DMA BD
// config word. See ``python/iron/sparse.py`` for the discardable-attr
// contract; see AM020 Ch. 2 p. 27 for the hardware bit. The default
// (no attrs on the ObjectFifoCreateOp) is the pre-existing behaviour:
// no discardable attr on the DMABDOp -> no compression bit set.
propagateSparseCompressionAttr(bdOp.getOperation(), op.getOperation(),
channelDir);
}
/// discardable attrs (set by ``aie.iron.sparse.SparseFifo.resolve``)
/// from the originating ObjectFifoCreateOp and, if the channel
/// direction selects the matching half of the
/// (compress_mm2s, decompress_s2mm) pair AND the BD lives on a
/// compute (AIE) tile, attach a discardable boolean
/// ``aie.enable_compression = true`` attribute on the new DMABDOp.
/// the cross-module footgun guard): the SparseFifo lowering
/// already attaches the intent to the ObjectFifoCreateOp; this
/// propagates it to the DMABDOp where the ObjectFifoCreateOp
/// itself is about to be erased.
///
/// Cross-module footgun (AM029 / aie_registers_aie2.json):
/// * Compute-tile MEMORY_MODULE DMA_BD0_1 bit 31 = Enable_Compression
/// * Memory-tile MEMORY_TILE_MODULE DMA_BD0_1 bits 31:26 = D0_Pad_Before
/// * Shim DMA: AM029 documents Enable_Compression for "AIE-ML
/// memory and AIE-ML tile DMA" only — not for shim.
/// Setting aie.enable_compression on a memtile or shim BD would
/// either silently corrupt an unrelated field (memtile) or set an
/// undocumented bit (shim). So we walk up to the BD's owning tile
/// and bail out unless it's a compute tile.
static void propagateSparseCompressionAttr(Operation *bdOp, Operation *fifoOp,
DMAChannelDir channelDir) {
if (!bdOp || !fifoOp)
return;
StringRef attrName;
if (channelDir == DMAChannelDir::MM2S) {
attrName = "aie.compress_mm2s";
} else if (channelDir == DMAChannelDir::S2MM) {
attrName = "aie.decompress_s2mm";
} else {
return;
}
auto enable = fifoOp->getAttrOfType<BoolAttr>(attrName);
if (!enable || !enable.getValue())
return;
// Cross-module footgun guard: only emit on compute-tile BDs. The
// BD lives in either MemOp (compute), MemTileDMAOp (memtile), or
// ShimDMAOp (shim). Walk up to find the parent and check the
// tile type via the device's target model.
TileOp tileOp;
if (auto memOp = bdOp->getParentOfType<MemOp>())
tileOp = memOp.getTileOp();
else if (bdOp->getParentOfType<MemTileDMAOp>() ||
bdOp->getParentOfType<ShimDMAOp>())
return; // memtile / shim — bit means something else (or undocumented).
else
return; // unknown parent; conservative skip.
if (!tileOp)
return;
auto deviceOp = tileOp->getParentOfType<DeviceOp>();
if (!deviceOp)
return;
const auto &targetModel = deviceOp.getTargetModel();
if (tileOp.isShimTile() ||
targetModel.isMemTile(tileOp.getCol(), tileOp.getRow()))
return;
bdOp->setAttr("aie.enable_compression",
BoolAttr::get(bdOp->getContext(), true));
}
/// Function that either calls createAIETileDMA(), createShimDMA() or
/// createMemTileDMA() based on op tile row value.
void createDMA(DeviceOp &device, OpBuilder &builder, ObjectFifoCreateOp op,
DMAChannelDir channelDir, int channelIndex, int lockMode,
BDDimLayoutArrayAttr dims, BDPadLayoutArrayAttr pad_dims,
std::optional<PacketInfoAttr> bdPacket,
ObjectFifoState &state) {
if (op.getProducerTileOp().isShimTile()) {
createShimDMA(device, builder, op, channelDir, channelIndex, lockMode,
dims, bdPacket, state);
} else if (op.getProducerTileOp().isMemTile()) {
BDPadLayoutArrayAttr padDims = nullptr;
if (channelDir == DMAChannelDir::MM2S && pad_dims)
padDims = pad_dims;
createMemTileDMA(device, builder, op, channelDir, channelIndex, lockMode,
dims, padDims, bdPacket, state);
} else {
createAIETileDMA(device, builder, op, channelDir, channelIndex, lockMode,
dims, bdPacket, state);
}
}
/// Function used to create a MemOp region with a DMA channel.
/// It uses creatBdBlock(), see there for lockMode input.
void createAIETileDMA(DeviceOp &device, OpBuilder &builder,
ObjectFifoCreateOp op, DMAChannelDir channelDir,
int channelIndex, int lockMode,
BDDimLayoutArrayAttr dims,
std::optional<PacketInfoAttr> bdPacket,
ObjectFifoState &state) {
size_t numBlocks = op.size();