MLIR-AIE 1.4.6.dev
AIELowerCoreIssuedConfiguration.cpp
Go to the documentation of this file.
1//===- AIELowerCoreIssuedConfiguration.cpp ----------------------*- C++ -*-===//
2//
3// Copyright (C) 2026 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7//
8// Lower the configuration a core makes onto the accesses it makes itself.
9//
10// The writes that push a task are not spelled out here. aie-codegen is asked to
11// push inside a transaction, and the transaction it records is read back and
12// replayed as stores the core makes over its processor bus. A restatement of
13// the register map would be one more copy to keep in step with aie-codegen.
14
15#include "TransactionBinary.h"
16
19#include "aie/Targets/AIERT.h"
20
21#include "mlir/Dialect/Arith/IR/Arith.h"
22#include "mlir/Dialect/Func/IR/FuncOps.h"
23#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
24#include "mlir/Dialect/SCF/IR/SCF.h"
25#include "mlir/IR/Builders.h"
26#include "mlir/Pass/Pass.h"
27
28namespace xilinx::AIE {
29#define GEN_PASS_DEF_AIELOWERCOREISSUEDCONFIGURATION
30#include "aie/Dialect/AIE/Transforms/AIEPasses.h.inc"
31} // namespace xilinx::AIE
32
33using namespace mlir;
34using namespace xilinx;
35using namespace xilinx::AIE;
36
37namespace {
38
39/// The core reaches its own tile's registers through a window at this offset;
40/// see the write_tm intrinsic, whose own default says the same.
41constexpr uint64_t kTileMemoryMappedBase = 0x80000;
42
43/// The names of the store and load intrinsics for this architecture.
44struct TileAccessIntrinsics {
45 std::string write, read;
46};
47
48static std::optional<TileAccessIntrinsics> tileAccessIntrinsics(AIEArch arch) {
49 switch (arch) {
50 case AIEArch::AIE2:
51 return TileAccessIntrinsics{"llvm.aie2.write.tm", "llvm.aie2.read.tm"};
52 case AIEArch::AIE2p:
53 return TileAccessIntrinsics{"llvm.aie2p.write.tm", "llvm.aie2p.read.tm"};
54 default:
55 return std::nullopt;
56 }
57}
58
59/// The writes aie-codegen makes to push `op`'s task, as (tile offset, value).
60static LogicalResult
61pushWrites(DmaPushQueueOp op, int col, int row,
62 const AIETargetModel &targetModel,
63 SmallVectorImpl<std::pair<uint64_t, uint32_t>> &writes) {
64 if (!op.getBdId())
65 return op.emitOpError("names its descriptor by tag; run "
66 "--aie-assign-bd-ids first");
67 AIERTControl ctl(targetModel);
68 if (failed(ctl.setIOBackend(/*aieSim=*/false, /*xaieDebug=*/false)))
69 return op.emitOpError("could not start aie-codegen to collect its writes");
70 ctl.startTransaction();
71 // Only the task queue. Rewriting the channel's control register while the
72 // channel runs loses the state it keeps between packets, and the channel
73 // this pushes onto is already configured and running.
74 if (failed(ctl.pushToBdQueueAndEnable(
75 *op.getOperation(), col, row, op.getChannel(), op.getDirection(),
76 op.getBdId().value_or(0), op.getRepeatCount(), /*padValue=*/0,
77 op.getOutOfOrder(), /*configureChannel=*/false)))
78 return failure();
79
80 std::vector<uint8_t> txn = ctl.exportSerializedTransaction();
81 std::vector<TransactionBinaryOperation> ops;
82 if (!parseTransactionBinary(txn, ops))
83 return op.emitOpError("could not read back what aie-codegen recorded");
84
85 // Only this tile's registers are the core's to write, and only a plain
86 // store is. Anything else means aie-codegen pushes a task in a way this
87 // lowering does not carry, and silently dropping it would leave the channel
88 // without the task.
89 uint64_t tileBase = targetModel.getTileAddress(col, row);
90 uint64_t tileSpan = 1ull << targetModel.getRowShift();
91 for (const TransactionBinaryOperation &txnOp : ops) {
92 if (txnOp.cmd.Opcode != XAie_TxnOpcode::XAIE_IO_WRITE)
93 return op.emitOpError("pushing this task takes a ")
94 << static_cast<int>(txnOp.cmd.Opcode)
95 << " transaction command, which a core cannot make; only plain "
96 "register writes lower here";
97 uint64_t addr = txnOp.cmd.RegOff;
98 if (addr < tileBase || addr >= tileBase + tileSpan)
99 return op.emitOpError("pushing this task writes ")
100 << addr << ", outside tile (" << col << ", " << row
101 << "); a core reaches only its own tile's registers";
102 writes.emplace_back(addr - tileBase, txnOp.cmd.Value);
103 }
104 if (writes.empty())
105 return op.emitOpError("aie-codegen recorded no writes for this push");
106 return success();
107}
108
109struct AIELowerCoreIssuedConfigurationPass
110 : public xilinx::AIE::impl::AIELowerCoreIssuedConfigurationBase<
111 AIELowerCoreIssuedConfigurationPass> {
112
113 /// A declaration of `name`, inside the device, which is a symbol table of
114 /// its own, so that the calls resolve here; outlining the cores later takes
115 /// the declaration out to the module along with them.
116 func::FuncOp declare(DeviceOp device, StringRef name, TypeRange argTypes,
117 TypeRange resultTypes) {
118 if (auto decl = device.lookupSymbol<func::FuncOp>(name))
119 return decl;
120 OpBuilder builder(device.getContext());
121 builder.setInsertionPointToStart(device.getBody());
122 auto decl = func::FuncOp::create(
123 builder, device.getLoc(), name,
124 FunctionType::get(device.getContext(), argTypes, resultTypes));
125 decl.setPrivate();
126 return decl;
127 }
128
129 /// A pointer to `offset` in this tile's register window.
130 Value tilePointer(OpBuilder &builder, Location loc, uint64_t offset) {
131 Type i32 = builder.getI32Type();
132 Type ptr = LLVM::LLVMPointerType::get(builder.getContext());
133 Value addr = arith::ConstantOp::create(
134 builder, loc, i32,
135 builder.getI32IntegerAttr(
136 static_cast<int32_t>(kTileMemoryMappedBase + offset)));
137 return LLVM::IntToPtrOp::create(builder, loc, ptr, addr);
138 }
139
140 LogicalResult lowerPush(DmaPushQueueOp op, const AIETargetModel &targetModel,
141 func::FuncOp write) {
142 CoreOp core = op->getParentOfType<CoreOp>();
143 TileOp tile = core.getTileOp();
144 SmallVector<std::pair<uint64_t, uint32_t>> writes;
145 if (failed(
146 pushWrites(op, tile.getCol(), tile.getRow(), targetModel, writes)))
147 return failure();
148 // The configuration enables the bus for this core before it runs.
149 core.setProcessorBus(true);
150
151 OpBuilder builder(op);
152 Type i32 = builder.getI32Type();
153 for (auto [offset, value] : writes) {
154 Value valueOp = arith::ConstantOp::create(
155 builder, op.getLoc(), i32,
156 builder.getI32IntegerAttr(static_cast<int32_t>(value)));
157 Value addrPtr = tilePointer(builder, op.getLoc(), offset);
158 // A call to a declaration, not llvm.call_intrinsic: the intrinsic is
159 // the AIE backend's, and translation to LLVM IR runs against an LLVM
160 // that does not have it. A named callee is what the other AIE
161 // intrinsics the cores use are reached through too.
162 func::CallOp::create(builder, op.getLoc(), write,
163 ValueRange{valueOp, addrPtr});
164 }
165 op.erase();
166 return success();
167 }
168
169 LogicalResult lowerPoll(DmaPollForQueueSpaceOp op,
170 const AIETargetModel &targetModel,
171 func::FuncOp read) {
172 CoreOp core = op->getParentOfType<CoreOp>();
173 TileOp tile = core.getTileOp();
174 std::optional<uint32_t> statusAddr = targetModel.getDmaStatusAddress(
175 tile.getCol(), tile.getRow(), op.getChannel(), op.getDirection());
176 if (!statusAddr)
177 return op.emitOpError("this tile reports no DMA status register to read");
178 uint32_t mask = targetModel.getDmaTaskQueueSizeMask();
179 if (mask == 0)
180 return op.emitOpError(
181 "this tile reports no task-queue field in its DMA status");
182 core.setProcessorBus(true);
183
184 OpBuilder builder(op);
185 Location loc = op.getLoc();
186 Type i32 = builder.getI32Type();
187 uint32_t localAddr =
188 *statusAddr - targetModel.getTileAddress(tile.getCol(), tile.getRow());
189 Value addrPtr = tilePointer(builder, loc, localAddr);
190 Value maskOp = arith::ConstantOp::create(
191 builder, loc, i32,
192 builder.getI32IntegerAttr(static_cast<int32_t>(mask)));
193 // The field counts the tasks the queue holds, so it reads the depth
194 // exactly when the queue has no room left.
195 uint32_t full = targetModel.getDmaTaskQueueDepth()
196 << llvm::countr_zero(mask);
197 Value fullOp = arith::ConstantOp::create(
198 builder, loc, i32,
199 builder.getI32IntegerAttr(static_cast<int32_t>(full)));
200
201 // Read the field until it falls below the depth. The core does nothing
202 // else meanwhile.
203 auto loop = scf::WhileOp::create(builder, loc, TypeRange{}, ValueRange{});
204 OpBuilder::InsertionGuard guard(builder);
205 Block *before = builder.createBlock(&loop.getBefore());
206 builder.setInsertionPointToStart(before);
207 Value status = func::CallOp::create(builder, loc, read, ValueRange{addrPtr})
208 .getResult(0);
209 Value size = arith::AndIOp::create(builder, loc, status, maskOp);
210 Value isFull = arith::CmpIOp::create(builder, loc, arith::CmpIPredicate::eq,
211 size, fullOp);
212 scf::ConditionOp::create(builder, loc, isFull, ValueRange{});
213
214 Block *after = builder.createBlock(&loop.getAfter());
215 builder.setInsertionPointToStart(after);
216 scf::YieldOp::create(builder, loc, ValueRange{});
217
218 op.erase();
219 return success();
220 }
221
222 void runOnOperation() override {
223 DeviceOp device = getOperation();
224 const AIETargetModel &targetModel = device.getTargetModel();
225
226 SmallVector<DmaPushQueueOp> pushes;
227 SmallVector<DmaPollForQueueSpaceOp> polls;
228 device.walk([&](Operation *op) {
229 if (auto push = dyn_cast<DmaPushQueueOp>(op))
230 pushes.push_back(push);
231 else if (auto poll = dyn_cast<DmaPollForQueueSpaceOp>(op))
232 polls.push_back(poll);
233 });
234 if (pushes.empty() && polls.empty())
235 return;
236
237 std::optional<TileAccessIntrinsics> intrinsics =
238 tileAccessIntrinsics(targetModel.getTargetArch());
239 if (!intrinsics) {
240 Operation *first = pushes.empty() ? polls.front().getOperation()
241 : pushes.front().getOperation();
242 first->emitOpError("this device has no access a core can make to its "
243 "own tile's registers");
244 return signalPassFailure();
245 }
246
247 OpBuilder builder(device.getContext());
248 Type i32 = builder.getI32Type();
249 Type ptr = LLVM::LLVMPointerType::get(device.getContext());
250
251 if (!polls.empty()) {
252 func::FuncOp read = declare(device, intrinsics->read, {ptr}, {i32});
253 for (DmaPollForQueueSpaceOp op : polls)
254 if (failed(lowerPoll(op, targetModel, read)))
255 return signalPassFailure();
256 }
257 if (!pushes.empty()) {
258 func::FuncOp write =
259 declare(device, intrinsics->write, {i32, ptr}, TypeRange{});
260 for (DmaPushQueueOp op : pushes)
261 if (failed(lowerPush(op, targetModel, write)))
262 return signalPassFailure();
263 }
264 }
265};
266
267} // namespace
268
269std::unique_ptr<OperationPass<DeviceOp>>
271 return std::make_unique<AIELowerCoreIssuedConfigurationPass>();
272}
virtual uint32_t getTileAddress(int col, int row) const
Return the base address of the tile's window.
virtual AIEArch getTargetArch() const =0
Return the target architecture.
virtual uint32_t getDmaTaskQueueDepth() const =0
Return how many DMA tasks a single channel's task queue holds (unsupported = 0).
virtual uint32_t getDmaTaskQueueSizeMask() const
Return the mask selecting the live task-queue occupancy field within the getDmaStatusAddress() regist...
virtual std::optional< uint32_t > getDmaStatusAddress(int, int, int, AIE::DMAChannelDir) const
Return the address of the DMA status register for a channel, or nullopt when this target's layout has...
virtual uint32_t getRowShift() const =0
std::unique_ptr< mlir::OperationPass< DeviceOp > > createAIELowerCoreIssuedConfigurationPass()
std::optional< int > parseTransactionBinary(const std::vector< uint8_t > &data, std::vector< TransactionBinaryOperation > &ops)
Parse an exported transaction.