MLIR-AIE 1.4.6.dev
AIEInsertTraceFlows.cpp
Go to the documentation of this file.
1//===- AIEInsertTraceFlows.cpp ----------------------------------*- C++ -*-===//
2//
3// Copyright (C) 2026 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7
14
15#include "mlir/Dialect/Arith/IR/Arith.h"
16#include "mlir/IR/Attributes.h"
17#include "mlir/Pass/Pass.h"
18
19#include "llvm/ADT/STLExtras.h"
20
21#include <climits>
22#include <map>
23#include <set>
24
25namespace xilinx::AIE {
26#define GEN_PASS_DEF_AIEINSERTTRACEFLOWS
27#include "aie/Dialect/AIE/Transforms/AIEPasses.h.inc"
28} // namespace xilinx::AIE
29
30using namespace mlir;
31using namespace xilinx;
32using namespace xilinx::AIE;
33
34namespace {
35
36struct TraceInfo {
37 TraceOp traceOp;
38 TileOp tile;
39 int packetId;
40 TracePacketType packetType;
41 WireBundle tracePort; // Trace:0 (core) or Trace:1 (mem)
42 int traceChannel; // Port number (0 for core, 1 for mem)
43 std::optional<int>
44 startBroadcast; // Broadcast channel for timer sync (if any)
45 std::optional<int> stopBroadcast; // Broadcast channel for trace stop (if any)
46};
47
48/// Per-channel DMA resource allocation.
49struct ChannelDescriptor {
50 int channel; // S2MM channel number
51 int bdId; // Buffer descriptor ID
52};
53
54struct ShimInfo {
55 TileOp shimTile;
56 int channel; // S2MM channel
57 int bdId; // Buffer descriptor ID
58 std::vector<TraceInfo> traceSources; // All traces routed to this shim
59 std::optional<int> startBroadcast; // Broadcast to trigger for start
60 std::optional<int> stopBroadcast; // Broadcast to trigger for stop
61 std::vector<ChannelDescriptor> channels; // Per-channel descriptors
62 std::vector<int> traceChannelAssignment; // Per-trace index into channels
63};
64
65/// The trace buffer of one runtime sequence. The trace units and the routes
66/// belong to the device; the buffer belongs to the sequence.
67struct SequenceTraceConfig {
68 RuntimeSequenceOp seq;
69 int bufferSizeBytes;
70 bool reuseOutputBuffer;
71 int bufferOffset; // byte offset of the trace data in the host buffer
72};
73
74// A dynamic (runtime-sized) runtime sequence carries its transfer sizes as
75// scalar block arguments (the dynamic ABI); its memref args are typed at
76// maximum capacity, not the runtime data size. Any non-memref block argument
77// marks it.
78static bool isDynamicRuntimeSequence(RuntimeSequenceOp seq) {
79 return llvm::any_of(seq.getBody().getArguments(), [](BlockArgument arg) {
80 return !isa<MemRefType>(arg.getType());
81 });
82}
83
84struct AIEInsertTraceFlowsPass
85 : xilinx::AIE::impl::AIEInsertTraceFlowsBase<AIEInsertTraceFlowsPass> {
86
87 void runOnOperation() override {
88 DeviceOp device = getOperation();
89 OpBuilder builder(device);
90 const auto &targetModel = device.getTargetModel();
91
92 // Verify no LogicalTileOps remain — placement must run before this pass
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 "
97 "first)";
98 hasLogicalTile = true;
99 });
100 if (hasLogicalTile)
101 return signalPassFailure();
102
103 // Phase 1: Collect all trace operations
104 SmallVector<TraceOp> traces;
105 device.walk([&](TraceOp trace) { traces.push_back(trace); });
106
107 if (traces.empty())
108 return;
109
110 // The trace DMA program and register writes below are AIE2-shaped.
111 if (isa<AIE4TargetModel>(targetModel)) {
112 traces.front().emitOpError("trace is not yet supported on AIE4");
113 return signalPassFailure();
114 }
115
116 // The trace DMA program below targets one of the two shim S2MM channels
117 // and a shim BD; reject options it cannot encode.
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();
123 }
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
129 << ")";
130 return signalPassFailure();
131 }
132
133 // Phase 1b: Collect every runtime_sequence with an aie.trace.host_config.
134 // Each one drives the trace units on its own dispatch, so each one gets a
135 // trace buffer and a shim DMA program.
136 SmallVector<RuntimeSequenceOp> runtimeSeqs;
137 SmallVector<TraceHostConfigOp> hostConfigs;
138 RuntimeSequenceOp firstSeq = nullptr;
139 for (auto seq : device.getBody()->getOps<RuntimeSequenceOp>()) {
140 if (!firstSeq)
141 firstSeq = seq;
142 for (auto hc : seq.getBody().front().getOps<TraceHostConfigOp>()) {
143 runtimeSeqs.push_back(seq);
144 hostConfigs.push_back(hc);
145 break;
146 }
147 }
148
149 // Require runtime_sequence when trace ops are present
150 if (!firstSeq) {
151 device.emitError()
152 << "aie.trace ops found but no runtime_sequence defined";
153 return signalPassFailure();
154 }
155
156 // Require trace.host_config in runtime_sequence
157 if (runtimeSeqs.empty()) {
158 firstSeq.emitError()
159 << "runtime_sequence with traces requires aie.trace.host_config";
160 return signalPassFailure();
161 }
162
163 // The packet flows and the stream switch configuration reach the hardware
164 // through the device, so the trace data of every sequence leaves the array
165 // through the same shim.
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)
172 continue;
173 InFlightDiagnostic err =
174 other.emitError()
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 "
178 "and egress column";
179 err.attachNote(hostConfig.getLoc()) << "first aie.trace.host_config here";
180 return signalPassFailure();
181 }
182
183 // The trace buffer is a host buffer, i.e. an argument of the runtime
184 // sequence.
185 //
186 // - Dedicated (default): append a fresh argument to the runtime sequence
187 // for the trace buffer. It lands at the tail, so enabling trace never
188 // perturbs the indices of the data arguments.
189 // - Reuse-output: trace data is written into the tail of the last
190 // existing argument (an output buffer), saving a host buffer. No new
191 // argument is added; the offset skips past the output data.
192 //
193 // Buffer size and reuse mode reach the hardware through the buffer
194 // descriptor that each sequence writes, so each sequence sets its own.
195 SmallVector<SequenceTraceConfig> seqConfigs;
196 for (auto [seq, hc] : llvm::zip(runtimeSeqs, hostConfigs)) {
197 SequenceTraceConfig cfg;
198 cfg.seq = seq;
199 cfg.bufferSizeBytes = hc.getBufferSize();
200 cfg.reuseOutputBuffer = hc.getReuseOutputBuffer();
201 cfg.bufferOffset = 0;
202 if (cfg.reuseOutputBuffer) {
203 auto args = seq.getBody().getArguments();
204 if (args.empty()) {
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();
209 }
210 if (isDynamicRuntimeSequence(seq)) {
211 seq.emitError()
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();
219 }
220 auto memrefType = cast<MemRefType>(args.back().getType());
221 cfg.bufferOffset = memrefType.getNumElements() *
222 (memrefType.getElementTypeBitWidth() / 8);
223 }
224 seqConfigs.push_back(cfg);
225 }
226
227 for (auto hc : hostConfigs)
228 hc.erase();
229
230 // Phase 2: Analyze traces and allocate resources
231 std::vector<TraceInfo> traceInfos;
232
233 // Precompute auto-allocated packet IDs in (col, row) order. Walking
234 // `traces` in IR order would make IDs depend on the order trace ops
235 // were emitted, which in turn depends on the placer's worker-to-tile
236 // mapping. Two placements that produce the same tile set would then
237 // get different trace overlays and exercise different routing-rule
238 // layouts -- a coupling that has produced false-match routing
239 // failures (e.g. mask=17 matching id 4 on a column-0 switch port).
240 // Sorting by (col, row) makes the id-to-tile binding a pure
241 // function of the active trace tile set.
242 llvm::DenseMap<Operation *, int> autoPacketIds;
243 {
244 // Wrapping past the max would alias two traces onto the same id.
245 const int kMaxPacketId = device.getTargetModel().getMaxPacketId();
246
247 // First pass: bucket traces and collect explicit ids. An explicit
248 // id reserves a slot the auto-allocator must avoid, and two
249 // explicit traces pinning the same id is a silent alias today.
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()) {
257 explicitPacket = p;
258 break;
259 }
260 }
261 }
262 if (!explicitPacket) {
263 autoIdTraces.push_back(trace);
264 continue;
265 }
266 int id = *explicitPacket.getId();
267 auto [it, inserted] = explicitIdOwner.try_emplace(id, explicitPacket);
268 if (!inserted) {
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();
277 }
278 }
279 // stable_sort so that multiple traces on the same tile (e.g. core
280 // + mem trace on the same core tile) get ids in their IR-emission
281 // order rather than an unspecified order.
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();
288 });
289 // From clPacketIdStart up, past ids user traces pinned and ids the
290 // device holds (PacketIdSpace).
291 PacketIdSpace held(device);
292 int next = clPacketIdStart;
293 for (auto trace : autoIdTraces) {
294 while (next <= kMaxPacketId &&
295 (explicitIdOwner.count(next) || held.isTaken(next)))
296 ++next;
297 if (next > kMaxPacketId) {
298 device.emitError()
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 "
305 << kMaxPacketId
306 << "); reduce the number of traced tiles, free up an explicit "
307 "id, or raise -packet-id-start only if you can spare the "
308 "lower IDs";
309 return signalPassFailure();
310 }
311 autoPacketIds[trace.getOperation()] = next++;
312 }
313 }
314
315 // Each (tile, trace unit) pair may be configured at most once: a hardware
316 // trace unit emits a single packet stream, so two aie.trace ops targeting
317 // the same unit would race on one packet id and corrupt routing. The
318 // packet type identifies the unit (Core/Mem/MemTile/ShimTile).
319 std::set<std::tuple<int, int, int>> seenTraceUnits; // (col, row, pktType)
320
321 for (auto trace : traces) {
322 auto tile = cast<TileOp>(trace.getTile().getDefiningOp());
323
324 // Find packet ID and type from trace body
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();
334 break;
335 }
336 }
337
338 // Determine packet type from tile type if not specified
339 if (!packetType) {
340 if (tile.isShimTile()) {
341 packetType = TracePacketType::ShimTile;
342 } else if (tile.isMemTile()) {
343 packetType = TracePacketType::MemTile;
344 } else {
345 // Core tile defaults to core type
346 packetType = TracePacketType::Core;
347 }
348 }
349
350 // Reject a second trace op on the same hardware unit of the same tile.
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 "
357 "configuration";
358 return signalPassFailure();
359 }
360
361 // Allocate packet ID if not specified (precomputed in (col, row)
362 // order above).
363 if (!packetId)
364 packetId = autoPacketIds.lookup(trace.getOperation());
365
366 // Make sure the in-IR TracePacketOp carries the (possibly
367 // auto-allocated) id so downstream passes (e.g.,
368 // -aie-trace-to-config) see consistent info.
369 if (!existingPacketOp) {
370 OpBuilder traceBuilder(&trace.getBody().front(),
371 trace.getBody().front().begin());
372 TracePacketOp::create(traceBuilder, trace.getLoc(),
373 traceBuilder.getI32IntegerAttr(*packetId),
374 *packetType);
375 } else if (!existingPacketOp.getId().has_value()) {
376 existingPacketOp.setIdAttr(
377 OpBuilder(existingPacketOp).getI32IntegerAttr(*packetId));
378 }
379
380 // Determine trace port based on packet type
381 WireBundle tracePort = WireBundle::Trace;
382 int traceChannel = 0;
383 if (*packetType == TracePacketType::Mem) {
384 traceChannel = 1; // Mem trace uses port 1
385 }
386
387 // Find start/stop configuration (broadcast or event)
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();
397 }
398 if (auto stopOp = dyn_cast<TraceStopEventOp>(op)) {
399 hasStopConfig = true;
400 if (stopOp.getBroadcast())
401 stopBroadcast = stopOp.getBroadcast();
402 }
403 }
404
405 // Require explicit start/stop configuration
406 if (!hasStartConfig) {
407 trace.emitError() << "trace is missing 'aie.trace.start'";
408 return signalPassFailure();
409 }
410 if (!hasStopConfig) {
411 trace.emitError() << "trace is missing 'aie.trace.stop'";
412 return signalPassFailure();
413 }
414
415 TraceInfo info;
416 info.traceOp = trace;
417 info.tile = tile;
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);
425 }
426
427 // Phase 2b: Select shim tiles based on routing strategy
428 std::map<int, ShimInfo> shimInfos; // col -> ShimInfo
429
430 if (routing == TraceShimRouting::Single) {
431 // All traces route to a single shim, controlled by the egress_shim_col
432 // parameter (default is 0).
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();
440 }
441 TileOp shimTile = nullptr;
442 for (auto tile : device.getOps<TileOp>()) {
443 if (tile.getCol() == targetCol && tile.getRow() == 0) {
444 shimTile = tile;
445 break;
446 }
447 }
448
449 if (!shimTile) {
450 builder.setInsertionPointToStart(&device.getRegion().front());
451 shimTile = TileOp::create(builder, device.getLoc(), targetCol, 0);
452 }
453
454 ShimInfo shimInfo;
455 shimInfo.shimTile = shimTile;
456 shimInfo.channel = clShimChannel;
457 shimInfo.bdId = clDefaultBdId;
458 shimInfo.traceSources = traceInfos;
459 // Collect broadcast channels from traces that use them
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;
465 }
466
467 // Map all source columns to the single shim
468 for (auto &info : traceInfos) {
469 int col = info.tile.getCol();
470 if (shimInfos.find(col) == shimInfos.end()) {
471 shimInfos[col] = shimInfo;
472 }
473 }
474 if (shimInfos.find(targetCol) == shimInfos.end()) {
475 shimInfos[targetCol] = shimInfo;
476 }
477 }
478
479 // Phase 2b-lateral: Optionally redirect shim targets to spare columns.
480 // This is a post-processing step that works with ANY routing strategy.
481 // When per-column routing returns, lateral routing will compose with it
482 // (each column's shim redirects to its nearest spare).
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());
488 });
489
490 // Collect all unique shim target columns and find redirects
491 std::map<int, int> redirects; // old target col -> new target col
492 for (auto &[col, shimInfo] : shimInfos) {
493 int curTarget = shimInfo.shimTile.getCol();
494 if (redirects.count(curTarget))
495 continue; // already computed
496
497 int spare = -1;
498 if (clLateralTargetCol >= 0) {
499 // Forced lateral target: always redirect unless it's a no-op.
500 if (clLateralTargetCol == curTarget)
501 continue;
502 // Validate the forced column is in range and is a shim NOC tile.
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();
510 }
511 spare = clLateralTargetCol;
512 } else {
513 // Auto-detect: only redirect from active columns to a spare.
514 if (activeColumns.count(curTarget) == 0)
515 continue; // already spare, no redirect needed
516 spare = findNearestSpareColumn(curTarget, activeColumns, targetModel);
517 }
518 if (spare >= 0)
519 redirects[curTarget] = spare;
520 }
521
522 // Apply redirects: rebuild shimInfos with new target columns
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);
531 }
532 newShimInfos[col] = shimInfo;
533 }
534 shimInfos = std::move(newShimInfos);
535 }
536 }
537
538 // Phase 2b-conflict: Check S2MM channel availability on target shims.
539 // If channels are occupied, adjust: use free channel, redirect lateral,
540 // or error.
541 auto usedChannels = scanUsedS2MMChannels(device);
542 auto s2mmChannels = [&](int col) {
543 return static_cast<int>(
544 targetModel.getNumDMAChannels(col, 0, DMAChannelDir::S2MM));
545 };
546
547 for (auto &[col, shimInfo] : shimInfos) {
548 int shimCol = shimInfo.shimTile.getCol();
549 auto usedIt = usedChannels.find(shimCol);
550 if (usedIt == usedChannels.end())
551 continue; // No conflicts on this shim
552
553 const auto &usedSet = usedIt->second;
554 int freeCount = s2mmChannels(shimCol) - static_cast<int>(usedSet.size());
555
556 if (freeCount <= 0) {
557 // No channels free -- try lateral redirect
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());
563 });
564 // Also treat columns with full shims as "active" for spare search
565 for (auto &[fullCol, channels] : usedChannels) {
566 if (static_cast<int>(channels.size()) >= s2mmChannels(fullCol))
567 activeColumns.insert(fullCol);
568 }
569 int spare =
570 findNearestSpareColumn(shimCol, activeColumns, targetModel);
571 if (spare >= 0) {
572 shimInfo.shimTile = getOrCreateShim(device, builder, spare);
573 // A spare has no core but can still carry one flow; it is not
574 // full, so its other channel is free.
575 shimInfo.channel = usedChannels[spare].count(clShimChannel)
576 ? 1 - clShimChannel
577 : clShimChannel;
578 continue;
579 }
580 }
581 // No lateral available -- emit error
582 device.emitError()
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();
588 }
589
590 if (freeCount == 1) {
591 // One channel free -- use it
592 int freeChannel = -1;
593 for (int ch = 0; ch < s2mmChannels(shimCol); ch++) {
594 if (usedSet.count(ch) == 0) {
595 freeChannel = ch;
596 break;
597 }
598 }
599 shimInfo.channel = freeChannel;
600 }
601 }
602
603 // Build channel descriptors and trace-to-channel assignments
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)
612 available.erase(ch);
613 }
614 shimInfo.channels =
615 buildChannelDescriptors(shimInfo.traceSources.size(),
616 shimInfo.channel, shimInfo.bdId, available);
617 // Round-robin assignment of traces to channels
618 for (size_t i = 0; i < shimInfo.traceSources.size(); i++) {
619 shimInfo.traceChannelAssignment.push_back(i % shimInfo.channels.size());
620 }
621 }
622
623 // Phase 2c: Rewrite broadcast to USER_EVENT for destination shim tiles
624 // (shim can't listen for its own broadcast)
625 for (auto &info : traceInfos) {
626 if (!info.tile.isShimTile())
627 continue;
628
629 int col = info.tile.getCol();
630 auto shimIt = shimInfos.find(col);
631 if (shimIt == shimInfos.end())
632 continue;
633
634 // Check if this traced shim tile IS the destination shim
635 if (shimIt->second.shimTile.getTileID() != info.tile.getTileID())
636 continue;
637
638 // This shim is both traced and the destination - rewrite start/stop ops
639 // to use USER_EVENT_1/0 instead of broadcast
640 for (auto &op : info.traceOp.getBody().getOps()) {
641 if (auto startOp = dyn_cast<TraceStartEventOp>(op)) {
642 if (startOp.getBroadcast()) {
643 // Replace broadcast with USER_EVENT_1
644 startOp->removeAttr("broadcast");
645 startOp->setAttr("event", TraceEventAttr::get(builder.getContext(),
646 builder.getStringAttr(
647 "USER_EVENT_1")));
648 }
649 }
650 if (auto stopOp = dyn_cast<TraceStopEventOp>(op)) {
651 if (stopOp.getBroadcast()) {
652 // Replace broadcast with USER_EVENT_0
653 stopOp->removeAttr("broadcast");
654 stopOp->setAttr("event", TraceEventAttr::get(builder.getContext(),
655 builder.getStringAttr(
656 "USER_EVENT_0")));
657 }
658 }
659 }
660
661 info.startBroadcast = std::nullopt;
662 info.stopBroadcast = std::nullopt;
663 }
664
665 // Phase 3: Insert packet flows
666 // Insert before the device terminator
667 Block &deviceBlock = device.getRegion().front();
668 builder.setInsertionPoint(deviceBlock.getTerminator());
669
670 for (auto &info : traceInfos) {
671 // Find target shim for this trace
672 int col = info.tile.getCol();
673 ShimInfo &shimInfo = shimInfos[col];
674
675 // Find this trace's channel assignment
676 int chanIdx = 0;
677 for (size_t i = 0; i < shimInfo.traceSources.size(); i++) {
678 if (shimInfo.traceSources[i].packetId == info.packetId) {
679 chanIdx = shimInfo.traceChannelAssignment[i];
680 break;
681 }
682 }
683 auto &chanDesc = shimInfo.channels[chanIdx];
684
685 // Create packet flow
686 auto packetFlowOp = PacketFlowOp::create(
687 builder, device.getLoc(), builder.getI8IntegerAttr(info.packetId),
688 nullptr, nullptr);
689
690 Block *flowBody = new Block();
691 packetFlowOp.getPorts().push_back(flowBody);
692 OpBuilder flowBuilder = OpBuilder::atBlockEnd(flowBody);
693
694 PacketSourceOp::create(flowBuilder, device.getLoc(),
695 Value(info.tile.getResult()), info.tracePort,
696 info.traceChannel);
697
698 PacketDestOp::create(flowBuilder, device.getLoc(),
699 Value(shimInfo.shimTile.getResult()),
700 WireBundle::DMA, chanDesc.channel);
701
702 EndOp::create(flowBuilder, device.getLoc());
703
704 packetFlowOp->setAttr("keep_pkt_header", builder.getBoolAttr(true));
705 }
706
707 // Phase 4: Program each runtime sequence to drain its own trace buffer.
708 for (const SequenceTraceConfig &cfg : seqConfigs) {
709 if (failed(emitSequenceTraceOps(cfg, traceInfos, shimInfos)))
710 return signalPassFailure();
711 }
712 }
713
714 /// Give `cfg.seq` a trace buffer and the shim DMA program that drains the
715 /// trace stream into it. `traceInfos` and `shimInfos` describe the
716 /// device-wide overlay, which every sequence of the device drives.
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;
725
726 // A second S2MM channel doubles the bytes the DMAs write. The host and
727 // -aie-fuse-trace-buffers read the byte count from the argument type, so
728 // the type must cover every channel.
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;
733
734 // `aiex.npu.address_patch` names the buffer by SSA value. `aiex.run` may
735 // inline this sequence into a caller with a different argument list.
736 Value traceBuffer;
737 BlockArgument appendedTraceArg; // null when reusing the output buffer
738 if (cfg.reuseOutputBuffer) {
739 traceBuffer = runtimeSeq.getBody().getArguments().back();
740 } else {
741 // An i8 memref makes the type state the buffer's byte size, which both
742 // the host and -aie-fuse-trace-buffers read.
743 appendedTraceArg = runtimeSeq.getBody().front().addArgument(
744 MemRefType::get({traceBytesClaimed},
745 IntegerType::get(device.getContext(), 8)),
746 runtimeSeq.getLoc());
747 traceBuffer = appendedTraceArg;
748 }
749
750 runtimeSeq.setTraceBufferAttr(TraceBufferAttr::get(
751 device.getContext(),
752 appendedTraceArg ? appendedTraceArg.getArgNumber()
753 : runtimeSeq.getBody().getNumArguments() - 1,
754 cfg.bufferOffset, traceBytesClaimed, bool(appendedTraceArg)));
755
756 Block &seqBlock = runtimeSeq.getBody().front();
757
758 // Find the last TraceStartConfigOp in the runtime sequence
759 Operation *lastStartConfig = nullptr;
760 for (auto &op : seqBlock.getOperations()) {
761 if (isa<TraceStartConfigOp>(op)) {
762 lastStartConfig = &op;
763 }
764 }
765
766 // Insert after the last start_config op, or at start if none found
767 if (lastStartConfig) {
768 builder.setInsertionPointAfter(lastStartConfig);
769 } else {
770 builder.setInsertionPointToStart(&seqBlock);
771 }
772
773 // 4b. Configure timer sync for tiles using broadcast-based start
774 std::set<std::tuple<int, int, bool>> processedTiles;
775 for (auto &info : traceInfos) {
776 if (!info.startBroadcast)
777 continue;
778
779 int col = info.tile.getCol();
780 int row = info.tile.getRow();
781 bool isMemTrace = info.packetType == TracePacketType::Mem;
782
783 if (processedTiles.count({col, row, isMemTrace}))
784 continue;
785 processedTiles.insert({col, row, isMemTrace});
786
787 // Skip destination shim tiles (handled in 4f)
788 if (info.tile.isShimTile()) {
789 auto shimIt = shimInfos.find(col);
790 if (shimIt != shimInfos.end() &&
791 shimIt->second.shimTile.getTileID() == info.tile.getTileID()) {
792 continue;
793 }
794 }
795
796 const RegisterInfo *timerReg = targetModel.lookupRegister(
797 "Timer_Control", info.tile.getTileID(), isMemTrace);
798 if (!timerReg)
799 return info.traceOp.emitError(
800 "Failed to lookup Timer_Control register");
801
802 std::string broadcastEventName;
803 if (info.tile.isShimTile()) {
804 broadcastEventName =
805 "BROADCAST_A_" + std::to_string(*info.startBroadcast);
806 } else {
807 broadcastEventName =
808 "BROADCAST_" + std::to_string(*info.startBroadcast);
809 }
810
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 << "'";
816 return failure();
817 }
818 const BitFieldInfo *resetField = timerReg->getField("Reset_Event");
819 if (!resetField)
820 return info.traceOp.emitError(
821 "Failed to lookup Reset_Event field in Timer_Control");
822 auto timerCtrlValue =
823 targetModel.encodeFieldValue(*resetField, *broadcastEvent);
824 if (!timerCtrlValue)
825 return info.traceOp.emitError("Broadcast event does not fit in "
826 "Timer_Control's Reset_Event field");
827
828 xilinx::AIEX::NpuWrite32Op::create(
829 builder, runtimeSeq.getLoc(),
830 AIEX::createConstantI32(builder, runtimeSeq.getLoc(),
831 timerReg->offset),
832 AIEX::createConstantI32(builder, runtimeSeq.getLoc(),
833 *timerCtrlValue),
834 nullptr, builder.getI32IntegerAttr(col),
835 builder.getI32IntegerAttr(row));
836 }
837
838 // 4c-4f. Insert per-shim configurations
839 std::set<int> configuredShimCols;
840 for (auto &[col, shimInfo] : shimInfos) {
841 int shimCol = shimInfo.shimTile.getCol();
842 if (!configuredShimCols.insert(shimCol).second)
843 continue;
844
845 for (auto [chanIdx, chanDesc] : llvm::enumerate(shimInfo.channels)) {
846 // Convert buffer size (bytes) to 32-bit words for buffer_length
847 int bufferLengthWords = bufferSizeBytes / 4;
848
849 // 4c. Write buffer descriptor
850 xilinx::AIEX::NpuWriteBdOp::create(
851 builder, runtimeSeq.getLoc(),
852 shimCol, // column
853 chanDesc.bdId, // bd_id
854 bufferLengthWords, // buffer_length (in 32-bit words)
855 0, // buffer_offset
856 1, // enable_packet
857 0, // out_of_order_id
858 0, // packet_id (not used for reception)
859 0, // packet_type (not used for reception)
860 0, 0, 0, 0, 0,
861 0, // d0_size, d0_stride, d1_size, d1_stride, d2_size, d2_stride
862 0, 0, 0, // iteration_current, iteration_size, iteration_stride
863 0, // next_bd
864 0, // row
865 0, // use_next_bd
866 1, // valid_bd
867 0, 0, 0, 0, 0, // lock_rel_val, lock_rel_id, lock_acq_enable,
868 // lock_acq_val, lock_acq_id
869 0, 0, 0, 0, 0, 0, // d0_zero_before, d1_zero_before, d2_zero_before,
870 // d0_zero_after, d1_zero_after, d2_zero_after
871 clTraceBurstLength, // burst_length
872 // axcache left unset: the blockwrite lowering resolves the
873 // target default, so baking it here would only duplicate it.
874 mlir::IntegerAttr(), /*channel=*/mlir::IntegerAttr(),
875 /*direction=*/DMAChannelDirAttr());
876
877 // 4d. Address patch -- the channels split the buffer between them, so
878 // channel i starts bufferSizeBytes past channel i-1.
879 uint32_t bdAddress = computeBDAddress(shimCol, chanDesc.bdId,
880 shimInfo.shimTile, targetModel);
881 int chanOffset =
882 cfg.bufferOffset + static_cast<int>(chanIdx) * bufferSizeBytes;
883 xilinx::AIEX::NpuAddressPatchOp::create(
884 builder, runtimeSeq.getLoc(), bdAddress, /*addr_val=*/mlir::Value(),
885 traceBuffer,
886 AIEX::createConstantI32(builder, runtimeSeq.getLoc(), chanOffset));
887
888 // 4e. DMA channel configuration — set Controller_ID from tile attribute
889 std::optional<uint32_t> ctrlAddr =
890 computeCtrlAddress(DMAChannelDir::S2MM, chanDesc.channel,
891 shimInfo.shimTile, targetModel);
892 if (!ctrlAddr)
893 return shimInfo.shimTile.emitError(
894 "Failed to lookup the S2MM control register");
895 ensureControllerIdAttr(shimInfo.shimTile, targetModel);
896 auto ctrlIdAttr =
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());
902 if (!ctrlReg)
903 return shimInfo.shimTile.emitError(llvm::Twine("Failed to lookup ") +
904 ctrlRegName);
905 const BitFieldInfo *ctrlIdField = ctrlReg->getField("Controller_ID");
906 if (!ctrlIdField)
907 return shimInfo.shimTile.emitError(
908 "Failed to lookup Controller_ID field in " +
909 llvm::Twine(ctrlRegName));
910 auto ctrlIdValue =
911 targetModel.encodeFieldValue(*ctrlIdField, ctrlIdAttr.assignedId());
912 if (!ctrlIdValue)
913 return shimInfo.shimTile.emitError(
914 "Controller ID does not fit in the Controller_ID field");
915 auto ctrlIdMask = targetModel.getFieldMask(*ctrlIdField);
916 if (!ctrlIdMask)
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(),
921 AIEX::createConstantI32(builder, runtimeSeq.getLoc(), *ctrlAddr),
922 AIEX::createConstantI32(builder, runtimeSeq.getLoc(), *ctrlIdValue),
923 AIEX::createConstantI32(builder, runtimeSeq.getLoc(), *ctrlIdMask),
924 nullptr, builder.getI32IntegerAttr(shimCol),
925 builder.getI32IntegerAttr(0));
926
927 // Push BD to task queue
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());
933 if (!queueReg)
934 return shimInfo.shimTile.emitError(llvm::Twine("Failed to lookup ") +
935 taskQueueRegName);
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);
943 auto bdIdValue =
944 targetModel.encodeFieldValue(*bdIdField, chanDesc.bdId);
945 if (!tokenValue)
946 return shimInfo.shimTile.emitError(
947 "Enable_Token_Issue does not fit in the field of " +
948 llvm::Twine(taskQueueRegName));
949 if (!bdIdValue)
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(),
956 AIEX::createConstantI32(builder, runtimeSeq.getLoc(),
957 queueReg->offset),
958 AIEX::createConstantI32(builder, runtimeSeq.getLoc(), queueValue),
959 nullptr, builder.getI32IntegerAttr(shimCol),
960 builder.getI32IntegerAttr(0));
961 }
962
963 // 4f. Shim timer and broadcast control (only if start broadcast is used)
964 if (shimInfo.startBroadcast) {
965 // Look up USER_EVENT_1 from target model (trigger event)
966 auto userEvent1 = targetModel.lookupEvent(
967 "USER_EVENT_1", shimInfo.shimTile.getTileID(), false);
968 if (!userEvent1)
969 return shimInfo.shimTile.emitError(
970 "Failed to lookup USER_EVENT_1 event");
971
972 const RegisterInfo *shimTimerReg = targetModel.lookupRegister(
973 "Timer_Control", shimInfo.shimTile.getTileID(), false);
974 if (!shimTimerReg)
975 return shimInfo.shimTile.emitError(
976 "Failed to lookup shim Timer_Control");
977 const BitFieldInfo *shimResetField =
978 shimTimerReg->getField("Reset_Event");
979 if (!shimResetField)
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(),
990 AIEX::createConstantI32(builder, runtimeSeq.getLoc(),
991 shimTimerReg->offset),
992 AIEX::createConstantI32(builder, runtimeSeq.getLoc(),
993 *shimTimerCtrlValue),
994 nullptr, builder.getI32IntegerAttr(shimCol),
995 builder.getI32IntegerAttr(0));
996
997 // Configure broadcast register with USER_EVENT_1
998 std::string broadcastRegName =
999 "Event_Broadcast" + std::to_string(*shimInfo.startBroadcast) + "_A";
1000 const RegisterInfo *broadcastReg = targetModel.lookupRegister(
1001 broadcastRegName, shimInfo.shimTile.getTileID());
1002 if (!broadcastReg)
1003 return shimInfo.shimTile.emitError(llvm::Twine("Failed to lookup ") +
1004 broadcastRegName);
1005 xilinx::AIEX::NpuWrite32Op::create(
1006 builder, runtimeSeq.getLoc(),
1007 AIEX::createConstantI32(builder, runtimeSeq.getLoc(),
1008 broadcastReg->offset),
1009 AIEX::createConstantI32(builder, runtimeSeq.getLoc(), *userEvent1),
1010 nullptr, builder.getI32IntegerAttr(shimCol),
1011 builder.getI32IntegerAttr(0));
1012
1013 // Generate USER_EVENT_1 to trigger the broadcast
1014 const RegisterInfo *eventGenReg = targetModel.lookupRegister(
1015 "Event_Generate", shimInfo.shimTile.getTileID());
1016 if (!eventGenReg)
1017 return shimInfo.shimTile.emitError(
1018 "Failed to lookup Event_Generate register");
1019 xilinx::AIEX::NpuWrite32Op::create(
1020 builder, runtimeSeq.getLoc(),
1021 AIEX::createConstantI32(builder, runtimeSeq.getLoc(),
1022 eventGenReg->offset),
1023 AIEX::createConstantI32(builder, runtimeSeq.getLoc(), *userEvent1),
1024 nullptr, builder.getI32IntegerAttr(shimCol),
1025 builder.getI32IntegerAttr(0));
1026 }
1027 }
1028
1029 // Phase 4g: Insert trace stop at end of runtime sequence
1030 builder.setInsertionPointToEnd(&seqBlock);
1031
1032 std::set<int> stoppedShimCols;
1033 for (auto &[col, shimInfo] : shimInfos) {
1034 if (!shimInfo.stopBroadcast)
1035 continue;
1036
1037 int shimCol = shimInfo.shimTile.getCol();
1038 if (!stoppedShimCols.insert(shimCol).second)
1039 continue;
1040
1041 auto userEvent0 = targetModel.lookupEvent(
1042 "USER_EVENT_0", shimInfo.shimTile.getTileID(), false);
1043 if (!userEvent0)
1044 return shimInfo.shimTile.emitError(
1045 "Failed to lookup USER_EVENT_0 event");
1046
1047 std::string broadcastRegName =
1048 "Event_Broadcast" + std::to_string(*shimInfo.stopBroadcast) + "_A";
1049 const RegisterInfo *broadcastReg = targetModel.lookupRegister(
1050 broadcastRegName, shimInfo.shimTile.getTileID());
1051 if (!broadcastReg)
1052 return shimInfo.shimTile.emitError(llvm::Twine("Failed to lookup ") +
1053 broadcastRegName);
1054 xilinx::AIEX::NpuWrite32Op::create(
1055 builder, runtimeSeq.getLoc(),
1056 AIEX::createConstantI32(builder, runtimeSeq.getLoc(),
1057 broadcastReg->offset),
1058 AIEX::createConstantI32(builder, runtimeSeq.getLoc(), *userEvent0),
1059 nullptr, builder.getI32IntegerAttr(shimCol),
1060 builder.getI32IntegerAttr(0));
1061
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(),
1069 AIEX::createConstantI32(builder, runtimeSeq.getLoc(),
1070 stopEventGenReg->offset),
1071 AIEX::createConstantI32(builder, runtimeSeq.getLoc(), *userEvent0),
1072 nullptr, builder.getI32IntegerAttr(shimCol),
1073 builder.getI32IntegerAttr(0));
1074 }
1075
1076 return success();
1077 }
1078
1079private:
1080 /// Ensure a tile has a controller_id attribute. If missing, assign one
1081 /// using the target model's mapping.
1082 void ensureControllerIdAttr(TileOp tile, const AIETargetModel &tm) {
1083 if (tile->hasAttr("controller_id"))
1084 return;
1085 auto idMap = tm.getTileToControllerIdMap();
1086 int pktId = idMap[{tile.colIndex(), tile.rowIndex()}];
1087 auto pktInfoAttr = PacketInfoAttr::get(tile->getContext(), 0, pktId);
1088 tile->setAttr("controller_id", pktInfoAttr);
1089 }
1090
1091 uint32_t computeBDAddress(int col, int bdId, TileOp shimTile,
1092 const AIETargetModel &tm) {
1093 int row = shimTile.getRow();
1094 return tm.getDmaBdAddress(col, row, bdId) +
1095 tm.getDmaBdAddressOffset(col, row);
1096 }
1097
1098 // Compute DMA control register address
1099 std::optional<uint32_t> computeCtrlAddress(DMAChannelDir dir, int channel,
1100 TileOp shimTile,
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";
1105 } else { // MM2S
1106 regName = (channel == 0) ? "DMA_MM2S_0_Ctrl" : "DMA_MM2S_1_Ctrl";
1107 }
1108 const RegisterInfo *reg = tm.lookupRegister(regName, shimTile.getTileID());
1109 if (!reg)
1110 return std::nullopt;
1111 return reg->offset;
1112 }
1113
1114 /// Build channel descriptors. Always includes the primary channel.
1115 /// Adds a secondary channel when distribute-channels is enabled and there
1116 /// are multiple traces. AIE2 shim tiles have exactly 2 S2MM DMA channels.
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;
1124 // Only add secondary channel if it's available (not claimed by existing
1125 // flows)
1126 if (availableChannels.count(ch2)) {
1127 chans.push_back({ch2, primaryBdId - 1});
1128 }
1129 }
1130 return chans;
1131 }
1132
1133 /// Find or create a shim tile at the given column.
1134 TileOp getOrCreateShim(DeviceOp device, OpBuilder &builder, int col) {
1135 for (auto tile : device.getOps<TileOp>()) {
1136 if (tile.getCol() == col && tile.getRow() == 0)
1137 return tile;
1138 }
1139 OpBuilder::InsertionGuard guard(builder);
1140 builder.setInsertionPointToStart(&device.getRegion().front());
1141 return TileOp::create(builder, device.getLoc(), col, 0);
1142 }
1143
1144 /// Scan the device for existing S2MM channel claims on shim tiles.
1145 /// Checks aie.flow destinations, aie.packet_flow destinations,
1146 /// ShimDMAAllocationOp declarations, aie.route DMA ends, and objectFifos
1147 /// that end at a shim.
1148 std::map<int, std::set<int>> scanUsedS2MMChannels(DeviceOp device) {
1149 std::map<int, std::set<int>> used; // shimCol -> set of used S2MM channels
1150
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());
1155 }
1156 });
1157
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());
1164 }
1165 }
1166 }
1167 });
1168
1169 device.walk([&](ShimDMAAllocationOp alloc) {
1170 if (alloc.getChannelDir() == DMAChannelDir::S2MM) {
1171 auto tile = alloc.getTileOp();
1172 used[tile.getCol()].insert(alloc.getChannelIndex());
1173 }
1174 });
1175
1176 // This pass runs before objectFifo lowering, so an objectFifo or route
1177 // that ends at a shim has no flow yet. Claim what its lowering will:
1178 // every pin first, then the lowest free S2MM channel for each unpinned
1179 // end, except that unpinned fifo ends take one per group allocation
1180 // shares, by the turns the design's #aie.consumed_by proofs give.
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)
1188 return;
1189 if (std::optional<int> pin = endpoint.getRouteChannel())
1190 used[tile.getCol()].insert(*pin);
1191 else
1192 unpinned.push_back(tile.getCol());
1193 });
1194 device.walk([&](ObjectFifoCreateOp fifo) {
1195 if (fifo.getPlio())
1196 return;
1197 for (auto [i, consumer] : llvm::enumerate(fifo.getConsumerTiles())) {
1198 auto tile = dyn_cast_or_null<TileOp>(consumer.getDefiningOp());
1199 if (!tile || !tile.isShimTile())
1200 continue;
1201 ObjectFifoEndPortAttr port = fifo.getConsumerPort(i);
1202 if (std::optional<int> pin = port ? port.channelIndex() : std::nullopt)
1203 used[tile.getCol()].insert(*pin);
1204 else
1205 unpinnedFifos[tile.getCol()].push_back(fifo.getSymNameAttr());
1206 }
1207 });
1208 std::optional<ShimTransferSpans> spans;
1209 for (auto &[col, fifos] : unpinnedFifos) {
1210 size_t groups = fifos.size();
1211 if (groups > 1) {
1212 if (!spans)
1213 spans.emplace(
1214 device,
1215 [&](StringAttr symbol) {
1216 return ShimTransferSpans::endOf(device, symbol);
1217 },
1218 Placer::provenShimGates(device));
1219 groups = spans->plan(fifos, fifos, {}).groups.size();
1220 }
1221 unpinned.append(groups, col);
1222 }
1223 for (int col : unpinned) {
1224 auto &channels = used[col];
1225 int ch = 0;
1226 while (channels.count(ch))
1227 ++ch;
1228 channels.insert(ch);
1229 }
1230
1231 return used;
1232 }
1233
1234 /// Find the nearest NOC shim column without active cores.
1235 /// Returns -1 if no spare column exists.
1236 int findNearestSpareColumn(int sourceCol, const std::set<int> &activeColumns,
1237 const AIETargetModel &targetModel) {
1238 int bestCol = -1;
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) {
1245 bestDist = dist;
1246 bestCol = c;
1247 }
1248 }
1249 }
1250 return bestCol;
1251 }
1252};
1253
1254} // namespace
1255
1256std::unique_ptr<OperationPass<DeviceOp>>
1258 return std::make_unique<AIEInsertTraceFlowsPass>();
1259}
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.