15#include "mlir/Dialect/Arith/IR/Arith.h"
16#include "mlir/IR/Attributes.h"
17#include "mlir/Pass/Pass.h"
19#include "llvm/ADT/STLExtras.h"
26#define GEN_PASS_DEF_AIEINSERTTRACEFLOWS
27#include "aie/Dialect/AIE/Transforms/AIEPasses.h.inc"
40 TracePacketType packetType;
45 std::optional<int> stopBroadcast;
49struct ChannelDescriptor {
58 std::vector<TraceInfo> traceSources;
59 std::optional<int> startBroadcast;
60 std::optional<int> stopBroadcast;
61 std::vector<ChannelDescriptor> channels;
62 std::vector<int> traceChannelAssignment;
67struct SequenceTraceConfig {
68 RuntimeSequenceOp seq;
70 bool reuseOutputBuffer;
78static bool isDynamicRuntimeSequence(RuntimeSequenceOp seq) {
79 return llvm::any_of(seq.getBody().getArguments(), [](BlockArgument arg) {
80 return !isa<MemRefType>(arg.getType());
84struct AIEInsertTraceFlowsPass
85 : xilinx::AIE::impl::AIEInsertTraceFlowsBase<AIEInsertTraceFlowsPass> {
87 void runOnOperation()
override {
88 DeviceOp device = getOperation();
89 OpBuilder builder(device);
90 const auto &targetModel = device.getTargetModel();
93 bool hasLogicalTile =
false;
94 device.walk([&](LogicalTileOp op) {
95 op.emitError() <<
"LogicalTileOp must be resolved to TileOp before "
96 "running -aie-insert-trace-flows (run -aie-place-tiles "
98 hasLogicalTile =
true;
101 return signalPassFailure();
104 SmallVector<TraceOp> traces;
105 device.walk([&](TraceOp trace) { traces.push_back(trace); });
111 if (isa<AIE4TargetModel>(targetModel)) {
112 traces.front().emitOpError(
"trace is not yet supported on AIE4");
113 return signalPassFailure();
118 int shimChannel = clShimChannel;
119 if (shimChannel < 0 || shimChannel > 1) {
120 device.emitError() <<
"shim-channel " << shimChannel
121 <<
" is not a shim S2MM channel; expected 0 or 1";
122 return signalPassFailure();
124 uint32_t numShimBds = targetModel.getNumBDs(AIETileType::ShimNOCTile);
125 int bdId = clDefaultBdId;
126 if (bdId < 0 ||
static_cast<uint32_t
>(bdId) >= numShimBds) {
127 device.emitError() <<
"default-bd-id " << bdId
128 <<
" is not a shim BD; expected [0, " << numShimBds
130 return signalPassFailure();
136 SmallVector<RuntimeSequenceOp> runtimeSeqs;
137 SmallVector<TraceHostConfigOp> hostConfigs;
138 RuntimeSequenceOp firstSeq =
nullptr;
139 for (
auto seq : device.getBody()->getOps<RuntimeSequenceOp>()) {
142 for (
auto hc : seq.getBody().front().getOps<TraceHostConfigOp>()) {
143 runtimeSeqs.push_back(seq);
144 hostConfigs.push_back(hc);
152 <<
"aie.trace ops found but no runtime_sequence defined";
153 return signalPassFailure();
157 if (runtimeSeqs.empty()) {
159 <<
"runtime_sequence with traces requires aie.trace.host_config";
160 return signalPassFailure();
166 TraceHostConfigOp hostConfig = hostConfigs.front();
167 auto routing = hostConfig.getRouting();
168 int egressShimColFromIR = hostConfig.getEgressShimCol();
169 for (
auto other : ArrayRef(hostConfigs).drop_front()) {
170 if (other.getRouting() == routing &&
171 other.getEgressShimCol() == egressShimColFromIR)
173 InFlightDiagnostic err =
175 <<
"aie.trace.host_config routes trace data differently from another "
176 "runtime_sequence in this device; the routes live in the device's "
177 "stream switches, so every sequence must name the same routing "
179 err.attachNote(hostConfig.getLoc()) <<
"first aie.trace.host_config here";
180 return signalPassFailure();
195 SmallVector<SequenceTraceConfig> seqConfigs;
196 for (
auto [seq, hc] : llvm::zip(runtimeSeqs, hostConfigs)) {
197 SequenceTraceConfig cfg;
199 cfg.bufferSizeBytes = hc.getBufferSize();
200 cfg.reuseOutputBuffer = hc.getReuseOutputBuffer();
201 cfg.bufferOffset = 0;
202 if (cfg.reuseOutputBuffer) {
203 auto args = seq.getBody().getArguments();
205 seq.emitError() <<
"trace.host_config reuse_output_buffer "
206 "requires the runtime_sequence to have at "
207 "least one argument to reuse";
208 return signalPassFailure();
210 if (isDynamicRuntimeSequence(seq)) {
212 <<
"trace.host_config reuse_output_buffer=true cannot be used "
213 "with a dynamic (runtime-sized) runtime_sequence: the trace "
214 "offset would be computed from the last tensor's maximum "
215 "static size, not its runtime transfer size, so trace data "
216 "would be written past the output buffer. Use a separate "
217 "trace buffer instead (reuse_output_buffer=false)";
218 return signalPassFailure();
220 auto memrefType = cast<MemRefType>(args.back().getType());
221 cfg.bufferOffset = memrefType.getNumElements() *
222 (memrefType.getElementTypeBitWidth() / 8);
224 seqConfigs.push_back(cfg);
227 for (
auto hc : hostConfigs)
231 std::vector<TraceInfo> traceInfos;
242 llvm::DenseMap<Operation *, int> autoPacketIds;
245 const int kMaxPacketId = device.getTargetModel().getMaxPacketId();
250 SmallVector<TraceOp> autoIdTraces;
251 llvm::DenseMap<int, TracePacketOp> explicitIdOwner;
252 for (
auto trace : traces) {
253 TracePacketOp explicitPacket =
nullptr;
254 for (
auto &op : trace.getBody().getOps()) {
255 if (
auto p = dyn_cast<TracePacketOp>(op)) {
256 if (p.getId().has_value()) {
262 if (!explicitPacket) {
263 autoIdTraces.push_back(trace);
266 int id = *explicitPacket.getId();
267 auto [it, inserted] = explicitIdOwner.try_emplace(
id, explicitPacket);
269 InFlightDiagnostic err =
270 explicitPacket.emitError()
271 <<
"trace packet id " <<
id
272 <<
" is already used by another trace; explicit packet ids "
273 "must be unique across the device";
274 err.attachNote(it->second.getLoc())
275 <<
"previous use of packet id " << id;
276 return signalPassFailure();
282 llvm::stable_sort(autoIdTraces, [](TraceOp a, TraceOp b) {
283 auto ta = cast<TileOp>(a.getTile().getDefiningOp());
284 auto tb = cast<TileOp>(b.getTile().getDefiningOp());
285 if (ta.getCol() != tb.getCol())
286 return ta.getCol() < tb.getCol();
287 return ta.getRow() < tb.getRow();
291 PacketIdSpace held(device);
292 int next = clPacketIdStart;
293 for (
auto trace : autoIdTraces) {
294 while (next <= kMaxPacketId &&
295 (explicitIdOwner.count(next) || held.isTaken(next)))
297 if (next > kMaxPacketId) {
299 <<
"trace overlay needs " << autoIdTraces.size()
300 <<
" auto-allocated packet IDs starting at " << clPacketIdStart
301 <<
" (with " << explicitIdOwner.size()
302 <<
" id(s) reserved by explicit aie.trace.packet ops, and any "
303 "held by packet flows or pinned routes elsewhere in the "
304 "device), but the hardware packet-id field is 5 bits (max "
306 <<
"); reduce the number of traced tiles, free up an explicit "
307 "id, or raise -packet-id-start only if you can spare the "
309 return signalPassFailure();
311 autoPacketIds[trace.getOperation()] = next++;
319 std::set<std::tuple<int, int, int>> seenTraceUnits;
321 for (
auto trace : traces) {
322 auto tile = cast<TileOp>(trace.getTile().getDefiningOp());
325 std::optional<int> packetId;
326 std::optional<TracePacketType> packetType;
327 TracePacketOp existingPacketOp =
nullptr;
328 for (
auto &op : trace.getBody().getOps()) {
329 if (
auto packetOp = dyn_cast<TracePacketOp>(op)) {
330 existingPacketOp = packetOp;
331 if (
auto explicitId = packetOp.getId())
332 packetId = explicitId;
333 packetType = packetOp.getType();
340 if (tile.isShimTile()) {
341 packetType = TracePacketType::ShimTile;
342 }
else if (tile.isMemTile()) {
343 packetType = TracePacketType::MemTile;
346 packetType = TracePacketType::Core;
351 auto unitKey = std::make_tuple(tile.getCol(), tile.getRow(),
352 static_cast<int>(*packetType));
353 if (!seenTraceUnits.insert(unitKey).second) {
354 trace.emitError() <<
"tile (" << tile.getCol() <<
", " << tile.getRow()
355 <<
") is traced more than once on the same trace "
356 "unit; each unit can have only one trace "
358 return signalPassFailure();
364 packetId = autoPacketIds.lookup(trace.getOperation());
369 if (!existingPacketOp) {
370 OpBuilder traceBuilder(&trace.getBody().front(),
371 trace.getBody().front().begin());
372 TracePacketOp::create(traceBuilder, trace.getLoc(),
373 traceBuilder.getI32IntegerAttr(*packetId),
375 }
else if (!existingPacketOp.getId().has_value()) {
376 existingPacketOp.setIdAttr(
377 OpBuilder(existingPacketOp).getI32IntegerAttr(*packetId));
381 WireBundle tracePort = WireBundle::Trace;
382 int traceChannel = 0;
383 if (*packetType == TracePacketType::Mem) {
388 std::optional<int> startBroadcast;
389 std::optional<int> stopBroadcast;
390 bool hasStartConfig =
false;
391 bool hasStopConfig =
false;
392 for (
auto &op : trace.getBody().getOps()) {
393 if (
auto startOp = dyn_cast<TraceStartEventOp>(op)) {
394 hasStartConfig =
true;
395 if (startOp.getBroadcast())
396 startBroadcast = startOp.getBroadcast();
398 if (
auto stopOp = dyn_cast<TraceStopEventOp>(op)) {
399 hasStopConfig =
true;
400 if (stopOp.getBroadcast())
401 stopBroadcast = stopOp.getBroadcast();
406 if (!hasStartConfig) {
407 trace.emitError() <<
"trace is missing 'aie.trace.start'";
408 return signalPassFailure();
410 if (!hasStopConfig) {
411 trace.emitError() <<
"trace is missing 'aie.trace.stop'";
412 return signalPassFailure();
416 info.traceOp = trace;
418 info.packetId = *packetId;
419 info.packetType = *packetType;
420 info.tracePort = tracePort;
421 info.traceChannel = traceChannel;
422 info.startBroadcast = startBroadcast;
423 info.stopBroadcast = stopBroadcast;
424 traceInfos.push_back(info);
428 std::map<int, ShimInfo> shimInfos;
430 if (routing == TraceShimRouting::Single) {
433 int targetCol = egressShimColFromIR;
434 if (targetCol < 0 || targetCol >= targetModel.columns() ||
435 !targetModel.isShimNOCTile(targetCol, 0)) {
436 device.emitError() <<
"egress_shim_col " << targetCol
437 <<
" is not a valid shim NOC tile (device has "
438 << targetModel.columns() <<
" columns)";
439 return signalPassFailure();
441 TileOp shimTile =
nullptr;
442 for (
auto tile : device.getOps<TileOp>()) {
443 if (tile.getCol() == targetCol && tile.getRow() == 0) {
450 builder.setInsertionPointToStart(&device.getRegion().front());
451 shimTile = TileOp::create(builder, device.getLoc(), targetCol, 0);
455 shimInfo.shimTile = shimTile;
456 shimInfo.channel = clShimChannel;
457 shimInfo.bdId = clDefaultBdId;
458 shimInfo.traceSources = traceInfos;
460 for (
auto &trace : traceInfos) {
461 if (trace.startBroadcast && !shimInfo.startBroadcast)
462 shimInfo.startBroadcast = trace.startBroadcast;
463 if (trace.stopBroadcast && !shimInfo.stopBroadcast)
464 shimInfo.stopBroadcast = trace.stopBroadcast;
468 for (
auto &info : traceInfos) {
469 int col = info.tile.getCol();
470 if (shimInfos.find(col) == shimInfos.end()) {
471 shimInfos[col] = shimInfo;
474 if (shimInfos.find(targetCol) == shimInfos.end()) {
475 shimInfos[targetCol] = shimInfo;
483 if (clLateralRouting) {
484 std::set<int> activeColumns;
485 device.walk([&](CoreOp core) {
486 auto coreTile = cast<TileOp>(core.getTile().getDefiningOp());
487 activeColumns.insert(coreTile.getCol());
491 std::map<int, int> redirects;
492 for (
auto &[col, shimInfo] : shimInfos) {
493 int curTarget = shimInfo.shimTile.getCol();
494 if (redirects.count(curTarget))
498 if (clLateralTargetCol >= 0) {
500 if (clLateralTargetCol == curTarget)
503 int numCols = targetModel.columns();
504 if (clLateralTargetCol >= numCols ||
505 !targetModel.isShimNOCTile(clLateralTargetCol, 0)) {
506 device.emitError() <<
"lateral-target-col " << clLateralTargetCol
507 <<
" is not a valid shim NOC tile (device has "
508 << numCols <<
" columns)";
509 return signalPassFailure();
511 spare = clLateralTargetCol;
514 if (activeColumns.count(curTarget) == 0)
516 spare = findNearestSpareColumn(curTarget, activeColumns, targetModel);
519 redirects[curTarget] = spare;
523 if (!redirects.empty()) {
524 std::map<int, ShimInfo> newShimInfos;
525 for (
auto &[col, shimInfo] : shimInfos) {
526 int curTarget = shimInfo.shimTile.getCol();
527 auto it = redirects.find(curTarget);
528 if (it != redirects.end()) {
529 int newTarget = it->second;
530 shimInfo.shimTile = getOrCreateShim(device, builder, newTarget);
532 newShimInfos[col] = shimInfo;
534 shimInfos = std::move(newShimInfos);
541 auto usedChannels = scanUsedS2MMChannels(device);
542 auto s2mmChannels = [&](
int col) {
543 return static_cast<int>(
544 targetModel.getNumDMAChannels(col, 0, DMAChannelDir::S2MM));
547 for (
auto &[col, shimInfo] : shimInfos) {
548 int shimCol = shimInfo.shimTile.getCol();
549 auto usedIt = usedChannels.find(shimCol);
550 if (usedIt == usedChannels.end())
553 const auto &usedSet = usedIt->second;
554 int freeCount = s2mmChannels(shimCol) -
static_cast<int>(usedSet.size());
556 if (freeCount <= 0) {
558 if (clLateralRouting) {
559 std::set<int> activeColumns;
560 device.walk([&](CoreOp core) {
561 auto coreTile = cast<TileOp>(core.getTile().getDefiningOp());
562 activeColumns.insert(coreTile.getCol());
565 for (
auto &[fullCol, channels] : usedChannels) {
566 if (
static_cast<int>(channels.size()) >= s2mmChannels(fullCol))
567 activeColumns.insert(fullCol);
570 findNearestSpareColumn(shimCol, activeColumns, targetModel);
572 shimInfo.shimTile = getOrCreateShim(device, builder, spare);
575 shimInfo.channel = usedChannels[spare].count(clShimChannel)
583 <<
"no S2MM channels available on shim tile at column " << shimCol
584 <<
" (both channels in use by existing flows or objectFifos); "
585 "set egress_shim_col to a column with a free channel, or "
586 "enable lateral-routing to redirect to a spare column";
587 return signalPassFailure();
590 if (freeCount == 1) {
592 int freeChannel = -1;
593 for (
int ch = 0; ch < s2mmChannels(shimCol); ch++) {
594 if (usedSet.count(ch) == 0) {
599 shimInfo.channel = freeChannel;
604 for (
auto &[col, shimInfo] : shimInfos) {
605 int shimCol = shimInfo.shimTile.getCol();
606 std::set<int> available;
607 for (
int ch = 0; ch < s2mmChannels(shimCol); ch++)
608 available.insert(ch);
609 auto usedIt = usedChannels.find(shimCol);
610 if (usedIt != usedChannels.end()) {
611 for (
int ch : usedIt->second)
615 buildChannelDescriptors(shimInfo.traceSources.size(),
616 shimInfo.channel, shimInfo.bdId, available);
618 for (
size_t i = 0; i < shimInfo.traceSources.size(); i++) {
619 shimInfo.traceChannelAssignment.push_back(i % shimInfo.channels.size());
625 for (
auto &info : traceInfos) {
626 if (!info.tile.isShimTile())
629 int col = info.tile.getCol();
630 auto shimIt = shimInfos.find(col);
631 if (shimIt == shimInfos.end())
635 if (shimIt->second.shimTile.getTileID() != info.tile.getTileID())
640 for (
auto &op : info.traceOp.getBody().getOps()) {
641 if (
auto startOp = dyn_cast<TraceStartEventOp>(op)) {
642 if (startOp.getBroadcast()) {
644 startOp->removeAttr(
"broadcast");
645 startOp->setAttr(
"event", TraceEventAttr::get(builder.getContext(),
646 builder.getStringAttr(
650 if (
auto stopOp = dyn_cast<TraceStopEventOp>(op)) {
651 if (stopOp.getBroadcast()) {
653 stopOp->removeAttr(
"broadcast");
654 stopOp->setAttr(
"event", TraceEventAttr::get(builder.getContext(),
655 builder.getStringAttr(
661 info.startBroadcast = std::nullopt;
662 info.stopBroadcast = std::nullopt;
667 Block &deviceBlock = device.getRegion().front();
668 builder.setInsertionPoint(deviceBlock.getTerminator());
670 for (
auto &info : traceInfos) {
672 int col = info.tile.getCol();
673 ShimInfo &shimInfo = shimInfos[col];
677 for (
size_t i = 0; i < shimInfo.traceSources.size(); i++) {
678 if (shimInfo.traceSources[i].packetId == info.packetId) {
679 chanIdx = shimInfo.traceChannelAssignment[i];
683 auto &chanDesc = shimInfo.channels[chanIdx];
686 auto packetFlowOp = PacketFlowOp::create(
687 builder, device.getLoc(), builder.getI8IntegerAttr(info.packetId),
690 Block *flowBody =
new Block();
691 packetFlowOp.getPorts().push_back(flowBody);
692 OpBuilder flowBuilder = OpBuilder::atBlockEnd(flowBody);
694 PacketSourceOp::create(flowBuilder, device.getLoc(),
695 Value(info.tile.getResult()), info.tracePort,
698 PacketDestOp::create(flowBuilder, device.getLoc(),
699 Value(shimInfo.shimTile.getResult()),
700 WireBundle::DMA, chanDesc.channel);
702 EndOp::create(flowBuilder, device.getLoc());
704 packetFlowOp->setAttr(
"keep_pkt_header", builder.getBoolAttr(
true));
708 for (
const SequenceTraceConfig &cfg : seqConfigs) {
709 if (failed(emitSequenceTraceOps(cfg, traceInfos, shimInfos)))
710 return signalPassFailure();
717 LogicalResult emitSequenceTraceOps(
const SequenceTraceConfig &cfg,
718 std::vector<TraceInfo> &traceInfos,
719 std::map<int, ShimInfo> &shimInfos) {
720 DeviceOp device = getOperation();
721 OpBuilder builder(device);
722 const auto &targetModel = device.getTargetModel();
723 RuntimeSequenceOp runtimeSeq = cfg.seq;
724 int bufferSizeBytes = cfg.bufferSizeBytes;
729 size_t maxChannels = 1;
730 for (
auto &[col, shimInfo] : shimInfos)
731 maxChannels = std::max(maxChannels, shimInfo.channels.size());
732 int traceBytesClaimed =
static_cast<int>(maxChannels) * bufferSizeBytes;
737 BlockArgument appendedTraceArg;
738 if (cfg.reuseOutputBuffer) {
739 traceBuffer = runtimeSeq.getBody().getArguments().back();
743 appendedTraceArg = runtimeSeq.getBody().front().addArgument(
744 MemRefType::get({traceBytesClaimed},
745 IntegerType::get(device.getContext(), 8)),
746 runtimeSeq.getLoc());
747 traceBuffer = appendedTraceArg;
750 runtimeSeq.setTraceBufferAttr(TraceBufferAttr::get(
752 appendedTraceArg ? appendedTraceArg.getArgNumber()
753 : runtimeSeq.getBody().getNumArguments() - 1,
754 cfg.bufferOffset, traceBytesClaimed,
bool(appendedTraceArg)));
756 Block &seqBlock = runtimeSeq.getBody().front();
759 Operation *lastStartConfig =
nullptr;
760 for (
auto &op : seqBlock.getOperations()) {
761 if (isa<TraceStartConfigOp>(op)) {
762 lastStartConfig = &op;
767 if (lastStartConfig) {
768 builder.setInsertionPointAfter(lastStartConfig);
770 builder.setInsertionPointToStart(&seqBlock);
774 std::set<std::tuple<int, int, bool>> processedTiles;
775 for (
auto &info : traceInfos) {
776 if (!info.startBroadcast)
779 int col = info.tile.getCol();
780 int row = info.tile.getRow();
781 bool isMemTrace = info.packetType == TracePacketType::Mem;
783 if (processedTiles.count({col, row, isMemTrace}))
785 processedTiles.insert({col, row, isMemTrace});
788 if (info.tile.isShimTile()) {
789 auto shimIt = shimInfos.find(col);
790 if (shimIt != shimInfos.end() &&
791 shimIt->second.shimTile.getTileID() == info.tile.getTileID()) {
796 const RegisterInfo *timerReg = targetModel.lookupRegister(
797 "Timer_Control", info.tile.getTileID(), isMemTrace);
799 return info.traceOp.emitError(
800 "Failed to lookup Timer_Control register");
802 std::string broadcastEventName;
803 if (info.tile.isShimTile()) {
805 "BROADCAST_A_" + std::to_string(*info.startBroadcast);
808 "BROADCAST_" + std::to_string(*info.startBroadcast);
811 auto broadcastEvent = targetModel.lookupEvent(
812 broadcastEventName, info.tile.getTileID(), isMemTrace);
813 if (!broadcastEvent) {
814 info.traceOp.emitError() <<
"Failed to lookup broadcast event '"
815 << broadcastEventName <<
"'";
818 const BitFieldInfo *resetField = timerReg->
getField(
"Reset_Event");
820 return info.traceOp.emitError(
821 "Failed to lookup Reset_Event field in Timer_Control");
822 auto timerCtrlValue =
823 targetModel.encodeFieldValue(*resetField, *broadcastEvent);
825 return info.traceOp.emitError(
"Broadcast event does not fit in "
826 "Timer_Control's Reset_Event field");
828 xilinx::AIEX::NpuWrite32Op::create(
829 builder, runtimeSeq.getLoc(),
834 nullptr, builder.getI32IntegerAttr(col),
835 builder.getI32IntegerAttr(row));
839 std::set<int> configuredShimCols;
840 for (
auto &[col, shimInfo] : shimInfos) {
841 int shimCol = shimInfo.shimTile.getCol();
842 if (!configuredShimCols.insert(shimCol).second)
845 for (
auto [chanIdx, chanDesc] : llvm::enumerate(shimInfo.channels)) {
847 int bufferLengthWords = bufferSizeBytes / 4;
850 xilinx::AIEX::NpuWriteBdOp::create(
851 builder, runtimeSeq.getLoc(),
874 mlir::IntegerAttr(), mlir::IntegerAttr(),
875 DMAChannelDirAttr());
879 uint32_t bdAddress = computeBDAddress(shimCol, chanDesc.bdId,
880 shimInfo.shimTile, targetModel);
882 cfg.bufferOffset +
static_cast<int>(chanIdx) * bufferSizeBytes;
883 xilinx::AIEX::NpuAddressPatchOp::create(
884 builder, runtimeSeq.getLoc(), bdAddress, mlir::Value(),
889 std::optional<uint32_t> ctrlAddr =
890 computeCtrlAddress(DMAChannelDir::S2MM, chanDesc.channel,
891 shimInfo.shimTile, targetModel);
893 return shimInfo.shimTile.emitError(
894 "Failed to lookup the S2MM control register");
895 ensureControllerIdAttr(shimInfo.shimTile, targetModel);
897 shimInfo.shimTile->getAttrOfType<PacketInfoAttr>(
"controller_id");
898 std::string ctrlRegName =
899 (chanDesc.channel == 0) ?
"DMA_S2MM_0_Ctrl" :
"DMA_S2MM_1_Ctrl";
900 const RegisterInfo *ctrlReg = targetModel.lookupRegister(
901 ctrlRegName, shimInfo.shimTile.getTileID());
903 return shimInfo.shimTile.emitError(llvm::Twine(
"Failed to lookup ") +
905 const BitFieldInfo *ctrlIdField = ctrlReg->
getField(
"Controller_ID");
907 return shimInfo.shimTile.emitError(
908 "Failed to lookup Controller_ID field in " +
909 llvm::Twine(ctrlRegName));
911 targetModel.encodeFieldValue(*ctrlIdField, ctrlIdAttr.assignedId());
913 return shimInfo.shimTile.emitError(
914 "Controller ID does not fit in the Controller_ID field");
915 auto ctrlIdMask = targetModel.getFieldMask(*ctrlIdField);
917 return shimInfo.shimTile.emitError(
918 "Controller_ID field does not fit in 32-bit register");
919 xilinx::AIEX::NpuMaskWrite32Op::create(
920 builder, runtimeSeq.getLoc(),
924 nullptr, builder.getI32IntegerAttr(shimCol),
925 builder.getI32IntegerAttr(0));
928 std::string taskQueueRegName = (chanDesc.channel == 0)
929 ?
"DMA_S2MM_0_Task_Queue"
930 :
"DMA_S2MM_1_Task_Queue";
931 const RegisterInfo *queueReg = targetModel.lookupRegister(
932 taskQueueRegName, shimInfo.shimTile.getTileID());
934 return shimInfo.shimTile.emitError(llvm::Twine(
"Failed to lookup ") +
936 const BitFieldInfo *tokenField =
937 queueReg->
getField(
"Enable_Token_Issue");
938 const BitFieldInfo *bdIdField = queueReg->
getField(
"Start_BD_ID");
939 if (!tokenField || !bdIdField)
940 return shimInfo.shimTile.emitError(
941 "Failed to lookup Enable_Token_Issue or Start_BD_ID fields");
942 auto tokenValue = targetModel.encodeFieldValue(*tokenField, 1);
944 targetModel.encodeFieldValue(*bdIdField, chanDesc.bdId);
946 return shimInfo.shimTile.emitError(
947 "Enable_Token_Issue does not fit in the field of " +
948 llvm::Twine(taskQueueRegName));
950 return shimInfo.shimTile.emitError(
951 "BD ID does not fit in the Start_BD_ID field of " +
952 llvm::Twine(taskQueueRegName));
953 uint32_t queueValue = *tokenValue | *bdIdValue;
954 xilinx::AIEX::NpuWrite32Op::create(
955 builder, runtimeSeq.getLoc(),
959 nullptr, builder.getI32IntegerAttr(shimCol),
960 builder.getI32IntegerAttr(0));
964 if (shimInfo.startBroadcast) {
966 auto userEvent1 = targetModel.lookupEvent(
967 "USER_EVENT_1", shimInfo.shimTile.getTileID(),
false);
969 return shimInfo.shimTile.emitError(
970 "Failed to lookup USER_EVENT_1 event");
972 const RegisterInfo *shimTimerReg = targetModel.lookupRegister(
973 "Timer_Control", shimInfo.shimTile.getTileID(),
false);
975 return shimInfo.shimTile.emitError(
976 "Failed to lookup shim Timer_Control");
977 const BitFieldInfo *shimResetField =
978 shimTimerReg->
getField(
"Reset_Event");
980 return shimInfo.shimTile.emitError(
981 "Failed to lookup Reset_Event in shim Timer_Control");
982 auto shimTimerCtrlValue =
983 targetModel.encodeFieldValue(*shimResetField, *userEvent1);
984 if (!shimTimerCtrlValue)
985 return shimInfo.shimTile.emitError(
986 "USER_EVENT_1 does not fit in shim "
987 "Timer_Control's Reset_Event field");
988 xilinx::AIEX::NpuWrite32Op::create(
989 builder, runtimeSeq.getLoc(),
993 *shimTimerCtrlValue),
994 nullptr, builder.getI32IntegerAttr(shimCol),
995 builder.getI32IntegerAttr(0));
998 std::string broadcastRegName =
999 "Event_Broadcast" + std::to_string(*shimInfo.startBroadcast) +
"_A";
1000 const RegisterInfo *broadcastReg = targetModel.lookupRegister(
1001 broadcastRegName, shimInfo.shimTile.getTileID());
1003 return shimInfo.shimTile.emitError(llvm::Twine(
"Failed to lookup ") +
1005 xilinx::AIEX::NpuWrite32Op::create(
1006 builder, runtimeSeq.getLoc(),
1010 nullptr, builder.getI32IntegerAttr(shimCol),
1011 builder.getI32IntegerAttr(0));
1014 const RegisterInfo *eventGenReg = targetModel.lookupRegister(
1015 "Event_Generate", shimInfo.shimTile.getTileID());
1017 return shimInfo.shimTile.emitError(
1018 "Failed to lookup Event_Generate register");
1019 xilinx::AIEX::NpuWrite32Op::create(
1020 builder, runtimeSeq.getLoc(),
1024 nullptr, builder.getI32IntegerAttr(shimCol),
1025 builder.getI32IntegerAttr(0));
1030 builder.setInsertionPointToEnd(&seqBlock);
1032 std::set<int> stoppedShimCols;
1033 for (
auto &[col, shimInfo] : shimInfos) {
1034 if (!shimInfo.stopBroadcast)
1037 int shimCol = shimInfo.shimTile.getCol();
1038 if (!stoppedShimCols.insert(shimCol).second)
1041 auto userEvent0 = targetModel.lookupEvent(
1042 "USER_EVENT_0", shimInfo.shimTile.getTileID(),
false);
1044 return shimInfo.shimTile.emitError(
1045 "Failed to lookup USER_EVENT_0 event");
1047 std::string broadcastRegName =
1048 "Event_Broadcast" + std::to_string(*shimInfo.stopBroadcast) +
"_A";
1049 const RegisterInfo *broadcastReg = targetModel.lookupRegister(
1050 broadcastRegName, shimInfo.shimTile.getTileID());
1052 return shimInfo.shimTile.emitError(llvm::Twine(
"Failed to lookup ") +
1054 xilinx::AIEX::NpuWrite32Op::create(
1055 builder, runtimeSeq.getLoc(),
1059 nullptr, builder.getI32IntegerAttr(shimCol),
1060 builder.getI32IntegerAttr(0));
1062 const RegisterInfo *stopEventGenReg = targetModel.lookupRegister(
1063 "Event_Generate", shimInfo.shimTile.getTileID());
1064 if (!stopEventGenReg)
1065 return shimInfo.shimTile.emitError(
1066 "Failed to lookup Event_Generate register");
1067 xilinx::AIEX::NpuWrite32Op::create(
1068 builder, runtimeSeq.getLoc(),
1070 stopEventGenReg->
offset),
1072 nullptr, builder.getI32IntegerAttr(shimCol),
1073 builder.getI32IntegerAttr(0));
1082 void ensureControllerIdAttr(TileOp tile,
const AIETargetModel &tm) {
1083 if (tile->hasAttr(
"controller_id"))
1086 int pktId = idMap[{tile.colIndex(), tile.rowIndex()}];
1087 auto pktInfoAttr = PacketInfoAttr::get(tile->getContext(), 0, pktId);
1088 tile->setAttr(
"controller_id", pktInfoAttr);
1091 uint32_t computeBDAddress(
int col,
int bdId, TileOp shimTile,
1092 const AIETargetModel &tm) {
1093 int row = shimTile.getRow();
1099 std::optional<uint32_t> computeCtrlAddress(DMAChannelDir dir,
int channel,
1101 const AIETargetModel &tm) {
1102 std::string regName;
1103 if (dir == DMAChannelDir::S2MM) {
1104 regName = (channel == 0) ?
"DMA_S2MM_0_Ctrl" :
"DMA_S2MM_1_Ctrl";
1106 regName = (channel == 0) ?
"DMA_MM2S_0_Ctrl" :
"DMA_MM2S_1_Ctrl";
1108 const RegisterInfo *reg = tm.
lookupRegister(regName, shimTile.getTileID());
1110 return std::nullopt;
1117 std::vector<ChannelDescriptor>
1118 buildChannelDescriptors(
size_t numTraces,
int primaryChannel,
int primaryBdId,
1119 const std::set<int> &availableChannels) {
1120 std::vector<ChannelDescriptor> chans;
1121 chans.push_back({primaryChannel, primaryBdId});
1122 if (clDistributeChannels && numTraces > 1 && primaryBdId > 0) {
1123 int ch2 = (primaryChannel == 1) ? 0 : 1;
1126 if (availableChannels.count(ch2)) {
1127 chans.push_back({ch2, primaryBdId - 1});
1134 TileOp getOrCreateShim(DeviceOp device, OpBuilder &builder,
int col) {
1135 for (
auto tile : device.getOps<TileOp>()) {
1136 if (tile.getCol() == col && tile.getRow() == 0)
1139 OpBuilder::InsertionGuard guard(builder);
1140 builder.setInsertionPointToStart(&device.getRegion().front());
1141 return TileOp::create(builder, device.getLoc(), col, 0);
1148 std::map<int, std::set<int>> scanUsedS2MMChannels(DeviceOp device) {
1149 std::map<int, std::set<int>> used;
1151 device.walk([&](FlowOp flow) {
1152 auto destTile = cast<TileOp>(flow.getDest().getDefiningOp());
1153 if (destTile.isShimTile() && flow.getDestBundle() == WireBundle::DMA) {
1154 used[destTile.getCol()].insert(flow.getDestChannel());
1158 device.walk([&](PacketFlowOp pktFlow) {
1159 for (
auto &op : pktFlow.getPorts().front()) {
1160 if (
auto dest = dyn_cast<PacketDestOp>(op)) {
1161 auto destTile = cast<TileOp>(dest.getTile().getDefiningOp());
1162 if (destTile.isShimTile() && dest.getBundle() == WireBundle::DMA) {
1163 used[destTile.getCol()].insert(dest.getChannel());
1169 device.walk([&](ShimDMAAllocationOp alloc) {
1170 if (alloc.getChannelDir() == DMAChannelDir::S2MM) {
1171 auto tile = alloc.getTileOp();
1172 used[tile.getCol()].insert(alloc.getChannelIndex());
1181 SmallVector<int> unpinned;
1182 std::map<int, SmallVector<StringAttr>> unpinnedFifos;
1183 device.walk([&](RouteEndpoint endpoint) {
1184 auto tile = dyn_cast_or_null<TileOp>(endpoint.getTile().getDefiningOp());
1185 if (!tile || !tile.isShimTile() ||
1186 endpoint.getRouteBundle() != WireBundle::DMA ||
1187 endpoint.getRouteDirection() != DMAChannelDir::S2MM)
1189 if (std::optional<int> pin = endpoint.getRouteChannel())
1190 used[tile.getCol()].insert(*pin);
1192 unpinned.push_back(tile.getCol());
1194 device.walk([&](ObjectFifoCreateOp fifo) {
1197 for (
auto [i, consumer] : llvm::enumerate(fifo.getConsumerTiles())) {
1198 auto tile = dyn_cast_or_null<TileOp>(consumer.getDefiningOp());
1199 if (!tile || !tile.isShimTile())
1201 ObjectFifoEndPortAttr port = fifo.getConsumerPort(i);
1202 if (std::optional<int> pin = port ? port.channelIndex() : std::nullopt)
1203 used[tile.getCol()].insert(*pin);
1205 unpinnedFifos[tile.getCol()].push_back(fifo.getSymNameAttr());
1208 std::optional<ShimTransferSpans> spans;
1209 for (
auto &[col, fifos] : unpinnedFifos) {
1210 size_t groups = fifos.size();
1215 [&](StringAttr symbol) {
1219 groups = spans->plan(fifos, fifos, {}).groups.size();
1221 unpinned.append(groups, col);
1223 for (
int col : unpinned) {
1224 auto &channels = used[col];
1226 while (channels.count(ch))
1228 channels.insert(ch);
1236 int findNearestSpareColumn(
int sourceCol,
const std::set<int> &activeColumns,
1237 const AIETargetModel &targetModel) {
1239 int bestDist = INT_MAX;
1240 int numCols = targetModel.
columns();
1241 for (
int c = 0; c < numCols; c++) {
1242 if (activeColumns.count(c) == 0 && targetModel.
isShimNOCTile(c, 0)) {
1243 int dist = std::abs(c - sourceCol);
1244 if (dist > 0 && dist < bestDist) {
1256std::unique_ptr<OperationPass<DeviceOp>>
1258 return std::make_unique<AIEInsertTraceFlowsPass>();
llvm::DenseMap< TileID, int > getTileToControllerIdMap(bool columnWiseUniqueIDs=true) const
Return a mapping from tile coordinates to controller IDs.
const RegisterInfo * lookupRegister(llvm::StringRef name, TileID tile, bool isMem=false) const
Register Database API - provides access to register and event information for trace configuration and...
virtual uint64_t getDmaBdAddress(int col, int row, uint32_t bd_id, int channel=-1, AIE::DMAChannelDir direction=AIE::DMAChannelDir::MM2S) const =0
Return the array address of the dma buffer descriptor for the given col, row, buffer descriptor id,...
virtual uint32_t getDmaBdAddressOffset(int col, int row) const =0
Return the offset of the base address field within the shim dma buffer descriptor.
bool isShimNOCTile(int col, int row) const
Return true if the given tile is a ShimNOC tile.
virtual int columns() const =0
Return the number of columns in the device.
static llvm::DenseMap< mlir::StringAttr, llvm::SmallVector< ShimTransferSpans::Gate > > provenShimGates(DeviceOp device)
static std::optional< End > endOf(DeviceOp device, mlir::StringAttr symbol)
The end a runtime sequence of device transfers through when it names symbol: a shim DMA route end,...
mlir::Value createConstantI32(mlir::OpBuilder &builder, mlir::Location loc, uint32_t value)
std::unique_ptr< mlir::OperationPass< DeviceOp > > createAIEInsertTraceFlowsPass()
const BitFieldInfo * getField(llvm::StringRef fieldName) const
Lookup a bit field by name, case-insensitively.