14#include "mlir/IR/Block.h"
15#include "mlir/IR/Builders.h"
16#include "mlir/IR/Region.h"
17#include "mlir/IR/ValueRange.h"
18#include "mlir/IR/Visitors.h"
19#include "mlir/Pass/Pass.h"
20#include "mlir/Support/LLVM.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/Support/MathExtras.h"
37#define GEN_PASS_DEF_AIEASSIGNBUFFERDESCRIPTORIDS
38#include "aie/Dialect/AIE/Transforms/AIEPasses.h.inc"
41#define DEBUG_TYPE "aie-assign-bd-ids"
52static constexpr uint32_t noPool = ~0u;
54SmallVector<uint32_t, 2> BdIdGenerator::poolsHolding(uint32_t bdId)
const {
55 SmallVector<uint32_t, 2> pools;
56 for (DMAChannelDir dir :
57 {DMAChannelDir::MM2S, DMAChannelDir::S2MM, DMAChannelDir::ControlMM2S,
58 DMAChannelDir::TraceS2MM}) {
63 numChannels = std::max(1, numChannels);
64 for (
int channel = 0; channel < numChannels; ++channel) {
67 !llvm::is_contained(pools, pool))
68 pools.push_back(pool);
72 pools.push_back(noPool);
76std::optional<uint32_t> BdIdGenerator::poolOf(
int channelIndex,
78 uint32_t bdId)
const {
92 for (uint32_t bdId = llvm::alignTo(first, alignment); bdId < last;
104 std::optional<uint32_t> pool = poolOf(channelIndex, dir, bdId);
108 "bdId has already been assigned");
114 std::optional<uint32_t> pool = poolOf(channelIndex, dir, bdId);
123 if (std::optional<uint32_t> pool = poolOf(channelIndex, dir, bdId))
129 if (std::optional<uint32_t> pool = poolOf(channelIndex, dir, bdId))
136 for (uint32_t pool : poolsHolding(bdId))
141 uint32_t bdId)
const {
142 if (std::optional<uint32_t> pool = poolOf(channelIndex, dir, bdId))
143 return reserved.count({*pool, bdId});
148 return llvm::any_of(poolsHolding(bdId), [&](uint32_t pool) {
149 return reserved.count({pool, bdId});
154 for (uint32_t pool : poolsHolding(bdId))
159 for (uint32_t pool : poolsHolding(bdId))
164 return llvm::any_of(poolsHolding(bdId), [&](uint32_t pool) {
170 uint32_t bdId)
const {
171 if (channelIndex < 0 ||
175 std::optional<uint32_t> pool = poolOf(channelIndex, dir, bdId);
178 return poolsHolding(bdId) == SmallVector<uint32_t, 2>{*pool};
181static constexpr StringLiteral reservedBdIdsAttr =
"aiex.reserved_bd_ids";
182static constexpr StringLiteral reservedChannelBdIdsAttr =
183 "aiex.reserved_channel_bd_ids";
186 return name == reservedBdIdsAttr || name == reservedChannelBdIdsAttr;
190 SmallVector<ReservedBdId> ids;
191 if (
auto flat = tile->getAttrOfType<DenseI32ArrayAttr>(reservedBdIdsAttr))
192 for (int32_t
id : flat.asArrayRef())
193 ids.push_back({std::nullopt,
id});
194 if (
auto perChannel =
195 tile->getAttrOfType<DictionaryAttr>(reservedChannelBdIdsAttr))
196 for (NamedAttribute entry : perChannel) {
197 auto [dirName, channelName] = entry.getName().getValue().rsplit(
'_');
198 std::optional<DMAChannelDir> dir = symbolizeDMAChannelDir(dirName);
200 auto list = dyn_cast<DenseI32ArrayAttr>(entry.getValue());
201 if (!dir || channelName.getAsInteger(10, channel) || !list)
203 for (int32_t
id : list.asArrayRef())
204 ids.push_back({std::make_pair(channel, *dir),
id});
210 MLIRContext *ctx = tile->getContext();
211 std::set<int32_t> flat;
212 std::map<std::string, std::set<int32_t>> perChannel;
218 auto [channel, dir] = *r.channel;
219 perChannel[(stringifyDMAChannelDir(dir) +
"_" + Twine(channel)).str()]
222 tile->removeAttr(reservedBdIdsAttr);
223 tile->removeAttr(reservedChannelBdIdsAttr);
225 tile->setAttr(reservedBdIdsAttr,
226 DenseI32ArrayAttr::get(
227 ctx, SmallVector<int32_t>(flat.begin(), flat.end())));
228 if (!perChannel.empty()) {
229 SmallVector<NamedAttribute> entries;
230 for (
auto &[key, channelIds] : perChannel)
231 entries.emplace_back(
232 StringAttr::get(ctx, key),
233 DenseI32ArrayAttr::get(
234 ctx, SmallVector<int32_t>(channelIds.begin(), channelIds.end())));
235 tile->setAttr(reservedChannelBdIdsAttr, DictionaryAttr::get(ctx, entries));
245static bool resolveResidentChannel(DeviceOp device, TileOp tile,
246 DMAChannelDir dir,
int channel,
247 uint32_t &headBdId, int32_t &repeatCount) {
248 auto scanRegion = [&](Region ®ion) ->
bool {
249 for (Block &block : region)
250 for (DMAStartOp startOp : block.getOps<DMAStartOp>()) {
251 if (startOp.getChannelDir() != dir ||
252 startOp.getChannelIndex() != channel)
254 Block *dest = startOp.getDest();
257 auto bds = dest->getOps<DMABDOp>();
260 DMABDOp head = *bds.begin();
261 if (!head.getBdId().has_value())
263 headBdId = head.getBdId().value();
264 repeatCount = startOp.getRepeatCount();
269 for (MemOp mem : device.getOps<MemOp>())
270 if (mem.getTile() == tile.getResult())
271 return scanRegion(mem->getRegion(0));
272 for (MemTileDMAOp mem : device.getOps<MemTileDMAOp>())
273 if (mem.getTile() == tile.getResult())
274 return scanRegion(mem->getRegion(0));
284static void populateRearmBindings(DeviceOp device) {
285 for (
auto binding : device.getOps<ObjectFifoRearmBindingOp>()) {
286 if (binding.getHeadBdIds().has_value() ||
287 binding.getRepeatCounts().has_value())
289 ValueRange tiles = binding.getChannelTiles();
290 ArrayRef<int32_t> dirs = binding.getChannelDirs();
291 ArrayRef<int32_t> chans = binding.getChannelIndices();
292 SmallVector<int32_t> headBdIds, repeatCounts;
293 bool resolvedAll =
true;
294 for (
unsigned i = 0; i < tiles.size(); ++i) {
295 auto tileOp = tiles[i].getDefiningOp<TileOp>();
297 dirs[i] == 0 ? DMAChannelDir::S2MM : DMAChannelDir::MM2S;
298 uint32_t headBdId = 0;
299 int32_t repeatCount = 0;
300 if (!tileOp || !resolveResidentChannel(device, tileOp, dir, chans[i],
301 headBdId, repeatCount)) {
305 headBdIds.push_back(
static_cast<int32_t
>(headBdId));
306 repeatCounts.push_back(repeatCount);
310 OpBuilder b(binding);
311 binding.setHeadBdIdsAttr(b.getDenseI32ArrayAttr(headBdIds));
312 binding.setRepeatCountsAttr(b.getDenseI32ArrayAttr(repeatCounts));
318 AIEAssignBufferDescriptorIDsPass> {
320 DeviceOp targetOp = getOperation();
322 return signalPassFailure();
325 auto memOps = llvm::to_vector_of<TileElement>(targetOp.getOps<MemOp>());
326 llvm::append_range(memOps, targetOp.getOps<MemTileDMAOp>());
327 llvm::append_range(memOps, targetOp.getOps<ShimDMAOp>());
333 for (TileElement memOp : memOps) {
334 int col = memOp.getTileID().col;
335 int row = memOp.getTileID().row;
338 gens.try_emplace(std::make_pair(col, row), col, row, targetModel);
340 if (emplaced.second) {
341 for (TileOp tile : targetOp.getOps<TileOp>()) {
342 if (tile.getCol() != col || tile.getRow() != row)
345 auto id =
static_cast<uint32_t
>(reserved.id);
346 if (reserved.channel) {
347 auto [channel, dir] = *reserved.channel;
363 int col, row, channel;
366 SmallVector<Assignment> assignments;
367 std::map<int32_t, SmallVector<size_t>> receiversOfTag;
368 for (TileElement memOp : memOps) {
369 DenseMap<Block *, std::pair<int, DMAChannelDir>> channels;
370 Region ®ion = memOp->getRegion(0);
371 for (Block &block : region)
372 for (
auto start : block.getOps<DMAStartOp>()) {
373 Block *dest = start.getDest();
374 while (dest && !channels.contains(dest)) {
375 channels[dest] = {start.getChannelIndex(), start.getChannelDir()};
376 dest = dest->hasNoSuccessors() ? nullptr : dest->getSuccessor(0);
379 memOp->walk([&](DMABDOp bd) {
380 std::pair<int, DMAChannelDir> channel = {0, DMAChannelDir::MM2S};
381 if (
auto dma = bd->getParentOfType<DMAOp>())
382 channel = {dma.getChannelIndex(), dma.getChannelDir()};
383 else if (
auto it = channels.find(bd->getBlock()); it != channels.end())
384 channel = it->second;
385 if (
auto tag = bd.getBdTag())
386 receiversOfTag[*tag].push_back(assignments.size());
387 assignments.push_back({bd, memOp.getTileID().col, memOp.getTileID().row,
388 channel.first, channel.second});
392 for (
auto &a : assignments) {
393 std::optional<int32_t>
id = a.bd.getBdId();
396 auto &gen = gens.at({a.col, a.row});
397 if (gen.bdIdAlreadyAssigned(a.channel, a.dir, *
id)) {
398 a.bd.emitOpError() <<
"assigned bd_id " << *
id
399 <<
" is already used by another BD on this tile";
400 return signalPassFailure();
402 gen.assignBdId(a.channel, a.dir, *
id);
407 for (
auto &[tag, indices] : receiversOfTag) {
408 if (indices.size() < 2)
410 std::optional<uint32_t> fixed;
411 for (
size_t i : indices) {
412 if (
auto id = assignments[i].bd.getBdId()) {
413 if (fixed && *fixed !=
static_cast<uint32_t
>(*
id)) {
414 assignments[i].bd.emitOpError(
415 "broadcast receiving buffers must have matching bd_id values "
418 return signalPassFailure();
423 auto available = [&, &indices = indices](uint32_t id) {
424 std::set<std::pair<int, int>> tiles;
425 for (
size_t i : indices) {
426 auto &a = assignments[i];
427 auto tile = std::make_pair(a.col, a.row);
428 if (!tiles.insert(tile).second ||
429 id >= targetModel.
getNumBDs(a.col, a.row) ||
433 gens.at(tile).bdIdAlreadyAssigned(a.channel, a.dir,
id)))
438 uint32_t
id = fixed.value_or(0);
439 auto &first = assignments[indices.front()];
440 uint32_t limit = targetModel.
getNumBDs(first.col, first.row);
442 while (
id < limit && !available(
id))
444 if (
id >= limit || !available(
id)) {
445 first.bd.emitOpError(
"cannot allocate a common bd_id for broadcast "
446 "receiving buffers with bd_tag ")
448 return signalPassFailure();
450 for (
size_t i : indices) {
451 auto &a = assignments[i];
452 if (!a.bd.getBdId()) {
453 gens.at({a.col, a.row}).assignBdId(a.channel, a.dir,
id);
458 for (
auto &a : assignments) {
459 auto &gen = gens.at({a.col, a.row});
460 if (
auto id = a.bd.getBdId()) {
464 <<
"assigned bd_id " << *
id <<
" is not accessible from channel "
465 << a.channel <<
" on this tile";
466 return signalPassFailure();
469 auto nextId = gen.nextBdId(a.channel, a.dir);
472 <<
"Allocator exhausted available BD IDs (maximum "
474 <<
" available for channel " << a.channel <<
").";
475 return signalPassFailure();
477 a.bd.setBdId(*nextId);
480 for (TileElement memOp : memOps) {
481 auto dmaOps = memOp.getOperation()->getRegion(0).getOps<DMAOp>();
482 if (!dmaOps.empty()) {
483 for (
auto dmaOp : dmaOps) {
484 auto bdRegions = dmaOp.getBds();
485 for (
auto *bdRegionIt = bdRegions.begin();
486 bdRegionIt != bdRegions.end();) {
487 auto &block = bdRegionIt->getBlocks().front();
488 DMABDOp bd = *block.getOps<DMABDOp>().begin();
489 std::optional<int> nextBdId;
490 if (++bdRegionIt != bdRegions.end())
492 (*bdRegionIt->getBlocks().front().getOps<DMABDOp>().begin())
494 else if (dmaOp.getLoop())
495 nextBdId = (*bdRegions.front()
501 bd.setNextBdId(nextBdId);
505 DenseMap<Block *, int> blockBdIdMap;
506 for (Block &block : memOp.getOperation()->getRegion(0)) {
507 if (block.getOps<DMABDOp>().empty())
509 DMABDOp bd = *block.getOps<DMABDOp>().begin();
510 auto bdId = bd.getBdId();
511 assert(bdId.has_value() &&
512 "DMABDOp should have bd_id assigned by now");
513 blockBdIdMap[&block] = *bdId;
516 for (Block &block : memOp.getOperation()->getRegion(0)) {
517 if (block.getOps<DMABDOp>().empty())
519 DMABDOp bd = *block.getOps<DMABDOp>().begin();
520 std::optional<int> nextBdId;
521 if (block.getNumSuccessors()) {
522 assert(llvm::range_size(block.getSuccessors()) == 1 &&
523 "should have only one successor block");
524 Block *nextBlock = block.getSuccessor(0);
525 if (blockBdIdMap.contains(nextBlock)) {
526 nextBdId = blockBdIdMap[nextBlock];
527 }
else if (nextBlock->getOperations().size() != 1 ||
528 !isa<EndOp>(nextBlock->getOperations().front())) {
529 bd.emitOpError(
"must be followed by a block with a dma_bd or "
530 "by a block with only aie.end");
531 return signalPassFailure();
533 bd.setNextBdId(nextBdId);
540 return signalPassFailure();
541 populateRearmBindings(targetOp);
546 DenseMap<int32_t, int> idOfTag;
547 DenseMap<std::pair<Value, int32_t>,
int> localIdOfTag;
548 WalkResult receivers = device.walk([&](DMABDOp bd) {
549 std::optional<uint32_t>
id = bd.getBdId();
550 if (std::optional<int32_t> tag = bd.getBdTag(); tag &&
id) {
551 auto tile = bd->getParentOfType<TileElement>();
553 localIdOfTag[{tile.getTile(), *tag}] = *id;
554 auto [it, inserted] = idOfTag.try_emplace(*tag, *
id);
555 if (!inserted && it->second !=
static_cast<int>(*
id)) {
556 bd.emitOpError(
"broadcast receiving buffers must have matching bd_id "
557 "values for bd_tag ")
559 return WalkResult::interrupt();
562 bd.removeBdTagAttr();
563 return WalkResult::advance();
565 if (receivers.wasInterrupted())
567 WalkResult walked = device.walk([&](DMABDOp bd) {
568 std::optional<int32_t> tag = bd.getOutOfOrderTag();
570 return WalkResult::advance();
571 auto it = idOfTag.find(*tag);
572 if (it == idOfTag.end()) {
573 bd.emitOpError(
"sends out of order into a descriptor that no "
574 "receiving tile holds");
575 return WalkResult::interrupt();
577 bd.setOutOfOrderId(it->second);
578 bd.removeOutOfOrderTagAttr();
579 return WalkResult::advance();
581 if (walked.wasInterrupted())
583 walked = device.walk([&](DmaPushQueueOp push) {
584 std::optional<int32_t> tag = push.getBdTag();
586 return WalkResult::advance();
587 Value tile = push->getParentOfType<CoreOp>().getTile();
588 auto it = localIdOfTag.find({tile, *tag});
589 if (it == localIdOfTag.end()) {
590 push.emitOpError(
"pushes a descriptor that this tile does not hold");
591 return WalkResult::interrupt();
593 push.setBdId(it->second);
594 push.removeBdTagAttr();
595 return WalkResult::advance();
597 return failure(walked.wasInterrupted());
601std::unique_ptr<OperationPass<DeviceOp>>
603 return std::make_unique<AIEAssignBufferDescriptorIDsPass>();
uint32_t getNumBDsForChannel(int col, int row, int channel, DMAChannelDir dir) const
bool isBdChannelAccessible(int col, int row, uint32_t bd_id, int channel, DMAChannelDir dir) const
virtual uint32_t getNumBDs(AIETileType tileType) const =0
Return the size of the BD id space of a tile type (see getTotalNumBDs()).
void setReservedBdIds(TileOp tile, llvm::ArrayRef< ReservedBdId > ids)
bool isReservedBdIdsAttr(llvm::StringRef name)
mlir::LogicalResult verifyDMAChannelsResolved(DeviceOp device)
std::unique_ptr< mlir::OperationPass< DeviceOp > > createAIEAssignBufferDescriptorIDsPass()
llvm::SmallVector< ReservedBdId > getReservedBdIds(TileOp tile)
WireBundle getDMAChannelBundle(DMAChannelDir dir)
The stream-switch bundle the channels of dir use.
void runOnOperation() override
LogicalResult resolveOutOfOrderTags(DeviceOp device)
Resolve BD tags after hardware ID assignment.
bool isReserved(int channelIndex, DMAChannelDir dir, uint32_t bdId) const
bool holdsTileWide(int channelIndex, DMAChannelDir dir, uint32_t bdId) const
const AIETargetModel & targetModel
std::set< std::pair< uint32_t, uint32_t > > alreadyAssigned
std::set< std::pair< uint32_t, uint32_t > > reserved
void reserveBdId(int channelIndex, DMAChannelDir dir, uint32_t bdId)
std::optional< uint32_t > nextBdId(int channelIndex, DMAChannelDir dir, uint32_t alignment=1)
void freeBdId(int channelIndex, DMAChannelDir dir, uint32_t bdId)
BdIdGenerator(int col, int row, const AIETargetModel &targetModel)
void assignBdId(int channelIndex, DMAChannelDir dir, uint32_t bdId)
bool bdIdAlreadyAssigned(int channelIndex, DMAChannelDir dir, uint32_t bdId)