MLIR-AIE 1.4.6.dev
AIEXToEmitC.cpp
Go to the documentation of this file.
1//===- AIEXToEmitC.cpp - AIEX runtime sequence to EmitC --------*- C++ -*-===//
2//
3// Copyright (C) 2026 Advanced Micro Devices, Inc.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7//
8// Converts npu transaction ops in an aie.runtime_sequence into EmitC calls to
9// aie/Runtime/TxnEncoding.h; translateToCpp() then yields a standalone C++
10// function assembling the same TXN words as the binary emitter
11// (AIETargetNPU.cpp), but runtime-parameterizable. A runtime-bound scf.for
12// (dynamic BD pool path) is preserved and lowered to emitc.for, keeping the
13// loop rolled at runtime.
14//
15//===----------------------------------------------------------------------===//
16
19
24
25#include "mlir/Conversion/ArithCommon/CeilFloorDivExpansion.h"
26#include "mlir/Conversion/ArithToEmitC/ArithToEmitC.h"
27#include "mlir/Conversion/SCFToEmitC/SCFToEmitC.h"
28#include "mlir/Dialect/Arith/IR/Arith.h"
29#include "mlir/Dialect/Arith/Transforms/Passes.h"
30#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
31#include "mlir/Dialect/EmitC/IR/EmitC.h"
32#include "mlir/Dialect/EmitC/Transforms/TypeConversions.h"
33#include "mlir/Dialect/MemRef/IR/MemRef.h"
34#include "mlir/Dialect/SCF/IR/SCF.h"
35#include "mlir/IR/Builders.h"
36#include "mlir/IR/BuiltinOps.h"
37#include "mlir/Interfaces/SideEffectInterfaces.h"
38#include "mlir/Pass/Pass.h"
39#include "mlir/Transforms/DialectConversion.h"
40#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
41#include "mlir/Transforms/RegionUtils.h"
42
43#include "llvm/ADT/StringSet.h"
44#include "llvm/ADT/TypeSwitch.h"
45#include "llvm/Support/Format.h"
46
47namespace xilinx {
48// DECL as well as DEF: the ConvertAIEXToEmitCPass(Options) constructor below
49// needs ConvertAIEXToEmitCOptions declared in this translation unit.
50#define GEN_PASS_DECL_CONVERTAIEXTOEMITC
51#define GEN_PASS_DEF_CONVERTAIEXTOEMITC
52#include "aie/Conversion/Passes.h.inc"
53} // namespace xilinx
54
55using namespace mlir;
56
57// The C++ that declines a build with a reason. `why` becomes a string
58// literal (quotes and backslashes escaped, line breaks flattened). When the
59// snippet goes through an emitc.verbatim with operands, `{}` is a
60// placeholder and `{{` its escape, so a `{` in the message is doubled; a
61// verbatim without operands is emitted literally.
62static std::string refuse(StringRef why, bool inFormat) {
63 std::string lit;
64 for (char ch : why) {
65 if (ch == '\n' || ch == '\r')
66 lit += ' ';
67 else if (ch == '"' || ch == '\\')
68 (lit += '\\') += ch;
69 else if (ch == '{' && inFormat)
70 lit += "{{";
71 else
72 lit += ch;
73 }
74 return "return aie_runtime::txn_refused(\"" + lit + "\");";
75}
76
77using namespace xilinx;
78
79namespace {
80
81// The C++ type of the TXN accumulator the generated function builds.
82constexpr llvm::StringLiteral kTxnVecType = "std::vector<uint32_t>";
83
84emitc::OpaqueType getU32Type(MLIRContext *ctx) {
85 return emitc::OpaqueType::get(ctx, "uint32_t");
86}
87
88// The C++ variable name of a runtime BD pool, declared in the generated
89// function's prologue. One pool per tile and BD partition: channels sharing a
90// partition must share one pool, or they would hand out the same id twice.
91template <typename PoolOp>
92std::string bdPoolName(PoolOp op) {
93 return "bd_pool_" + std::to_string(op.getColumn()) + "_" +
94 std::to_string(op.getRow()) + "_" + std::to_string(op.getBdBegin()) +
95 "_" + std::to_string(op.getBdEnd());
96}
97
98// A uint32_t literal operand (e.g. `42u`) for a txn_append_* argument. Used for
99// the compile-time-resolved address fields (buffer/col/row are folded in).
100Value u32Literal(OpBuilder &b, Location loc, uint32_t val) {
101 return emitc::ConstantOp::create(
102 b, loc, getU32Type(b.getContext()),
103 emitc::OpaqueAttr::get(b.getContext(), std::to_string(val) + "u"));
104}
105
106// Emit a call to a TxnEncoding.h free function on the txn vector. Scalar
107// operands pass through as-is; convert-arith-to-emitc later lowers them to C++
108// literals or function parameters, byte-identical to the static path.
109void emitTxnCall(OpBuilder &b, Location loc, StringRef fn, Value txnVec,
110 ValueRange args) {
111 SmallVector<Value> callArgs;
112 callArgs.push_back(txnVec);
113 callArgs.append(args.begin(), args.end());
114 emitc::CallOpaqueOp::create(b, loc, TypeRange{}, ("aie_runtime::" + fn).str(),
115 callArgs);
116}
117
118// Device-relative values (absolute addr, blockwrite data) resolved before the
119// ops are cloned out of the aie.device, keyed by their clone in the emitc.func.
120struct DeviceResolved {
121 llvm::DenseMap<Operation *, uint32_t> absoluteAddr;
122 llvm::DenseMap<Operation *, DenseIntElementsAttr> blockWriteData;
123};
124
125class AIEXToEmitCConverter {
126public:
127 AIEXToEmitCConverter(emitc::FuncOp funcOp, Value txnVec,
128 const DeviceResolved &resolved, Value opCountVar,
129 bool foldDDRAddrOffset)
130 : funcOp(funcOp), txnVec(txnVec), resolved(resolved),
131 opCountVar(opCountVar), foldDDRAddrOffset(foldDDRAddrOffset) {}
132
133 // Convert every npu/pool op in the body, recursing into scf regions. Returns
134 // the compile-time op count for a straight-line body (the literal op_count),
135 // or nullopt on error. With a runtime op-count var (a loop is present) each
136 // op increments it instead and the returned count is unused.
137 std::optional<uint32_t> run() {
138 // DMA lowering consumes buffer views but can leave dead subview/cast
139 // chains behind (notably after configure/run materialization). They are
140 // not transaction operations and must not reach the C++ converter.
141 bool erased;
142 do {
143 erased = false;
144 funcOp.walk([&](Operation *op) {
145 if (isa<memref::MemRefDialect>(op->getDialect()) &&
146 isOpTriviallyDead(op)) {
147 op->erase();
148 erased = true;
149 }
150 });
151 } while (erased);
152 uint32_t count = 0;
153 SmallVector<Operation *> consumed;
154 convertBlockRecursive(funcOp.getBlocks().front(), count, consumed);
155 if (!ok)
156 return std::nullopt;
157
158 // Erase the converted npu ops, then DCE their now-dead operand clones (a
159 // get_global feeding a blockwrite, a folded-away address constant). Region-
160 // scoped runRegionDCE, not a module canonicalizer: the latter would also
161 // drop the shared memref.global the blockwrite data was inlined from, which
162 // other sequences in the module still reference.
163 for (Operation *op : llvm::reverse(consumed))
164 op->erase();
165 IRRewriter rewriter(funcOp.getContext());
166 (void)runRegionDCE(rewriter, funcOp.getFunctionBody());
167 return count;
168 }
169
170private:
171 // Convert the npu/pool ops in `block`, recursing through scf op regions so a
172 // rolled loop's body is lowered in place (the scf.for itself is left for the
173 // later convert-scf-to-emitc step). Collects converted ops into `consumed`.
174 void convertBlockRecursive(Block &block, uint32_t &count,
175 SmallVector<Operation *> &consumed) {
176 SmallVector<Operation *> work;
177 for (Operation &op : block)
178 work.push_back(&op);
179 for (Operation *op : work) {
180 if (!ok)
181 return;
182 // Structural emitc ops and arith (constant / runtime-value math) are left
183 // for the later arith-to-emitc step. Recurse into scf ops (and any other
184 // region-carrying control flow) to convert their bodies; the control-flow
185 // op itself is handled by convert-scf-to-emitc afterwards.
186 if (isa<emitc::EmitCDialect, arith::ArithDialect>(op->getDialect()))
187 continue;
188 if (isa<scf::SCFDialect>(op->getDialect())) {
189 for (Region &r : op->getRegions())
190 for (Block &b : r)
191 convertBlockRecursive(b, count, consumed);
192 continue;
193 }
194 convertOne(op, count);
195 if (!isa<memref::GetGlobalOp>(op))
196 consumed.push_back(op);
197 }
198 }
199
200private:
201 // Record one emitted txn op: bump the compile-time count and, when a runtime
202 // op-count variable exists (the sequence has a loop, so the count is not
203 // known at compile time), emit a `++__opcount;` so the header gets the true
204 // runtime total.
205 void countOp(OpBuilder &b, Location loc, uint32_t &count) {
206 ++count;
207 if (opCountVar)
208 emitc::VerbatimOp::create(b, loc, "++{};", ValueRange{opCountVar});
209 }
210
211 // Convert one op, appending to the txn vector and incrementing `count`.
212 // Scalar operands flow through as SSA (lowered later by
213 // convert-arith-to-emitc); only the address field is replaced by its
214 // device-resolved literal. Unsupported ops set `ok` false.
215 void convertOne(Operation *op, uint32_t &count) {
216 OpBuilder b(op);
217 Location loc = op->getLoc();
218
219 llvm::TypeSwitch<Operation *, void>(op)
220 .Case<AIEX::NpuWrite32Op>([&](auto w) {
221 // A compile-time address folds to a literal; a runtime address (the
222 // dynamic BD pool's bdBase + wordIdx, arith over a popped id) is
223 // passed through as SSA and lowered by convert-arith-to-emitc.
224 Value addrV = runtimeOrResolvedAddr(b, loc, w, w.getAddress());
225 if (!addrV)
226 return fail(w, "cannot convert a symbolic/unresolved write32 "
227 "address to the C++ TXN target");
228 emitTxnCall(b, loc, "txn_append_write32", txnVec,
229 {addrV, w.getValue()});
230 countOp(b, loc, count);
231 })
232 .Case<AIEX::NpuMaskWrite32Op>([&](auto mw) {
233 Value addrV = runtimeOrResolvedAddr(b, loc, mw, mw.getAddress());
234 if (!addrV)
235 return fail(mw, "cannot convert a symbolic/unresolved maskwrite32 "
236 "address to the C++ TXN target");
237 emitTxnCall(b, loc, "txn_append_maskwrite32", txnVec,
238 {addrV, mw.getValue(), mw.getMask()});
239 countOp(b, loc, count);
240 })
241 .Case<AIEX::NpuMaskPollOp>([&](auto mp) {
242 Value addrV = runtimeOrResolvedAddr(b, loc, mp, mp.getAddress());
243 if (!addrV)
244 return fail(mp, "cannot convert a symbolic/unresolved maskpoll "
245 "address to the C++ TXN target");
246 emitTxnCall(b, loc, "txn_append_maskpoll32", txnVec,
247 {addrV, mp.getValue(), mp.getMask()});
248 countOp(b, loc, count);
249 })
250 .Case<AIEX::NpuSyncOp>([&](auto s) {
251 emitTxnCall(b, loc, "txn_append_sync", txnVec,
252 {s.getColumn(), s.getRow(), s.getDirection(),
253 s.getChannel(), s.getColumnNum(), s.getRowNum()});
254 countOp(b, loc, count);
255 })
256 .Case<AIEX::NpuLoadPdiOp>([&](auto pdi) {
257 Value address = emitc::ConstantOp::create(
258 b, loc, emitc::OpaqueType::get(b.getContext(), "uint64_t"),
259 emitc::OpaqueAttr::get(b.getContext(),
260 std::to_string(pdi.getAddress()) + "ULL"));
261 emitTxnCall(b, loc, "txn_append_loadpdi", txnVec,
262 {u32Literal(b, loc, pdi.getId()),
263 u32Literal(b, loc, pdi.getSize()), address});
264 countOp(b, loc, count);
265 })
266 .Case<AIEX::NpuPreemptOp>([&](auto preempt) {
267 emitTxnCall(b, loc, "txn_append_preempt", txnVec,
268 {u32Literal(b, loc, preempt.getLevel())});
269 countOp(b, loc, count);
270 })
271 .Case<AIEX::NpuAddressPatchOp>([&](auto ap) {
272 // A runtime bd_id makes the patched register address runtime: prefer
273 // the SSA addr_val (flows through arith-to-emitc) over the constant.
274 Value addrV = ap.getAddrVal() ? ap.getAddrVal()
275 : u32Literal(b, loc, ap.getAddr());
276 std::optional<uint32_t> argIdx = ap.getArgIdx();
277 if (!argIdx)
278 return fail(ap, "address_patch still names its host buffer by SSA "
279 "value; run -aie-resolve-address-patch-buffers");
280 Value idxV = emitc::ConstantOp::create(
281 b, loc, emitc::OpaqueType::get(b.getContext(), "int32_t"),
282 emitc::OpaqueAttr::get(b.getContext(), std::to_string(*argIdx)));
283 // txn_append_arg_patch applies the DDR-aperture fold itself, so the
284 // rule lives only in TxnEncoding.h. Both operands are literals here,
285 // so -O2 folds the branch away.
286 Value foldV = emitc::ConstantOp::create(
287 b, loc, emitc::OpaqueType::get(b.getContext(), "bool"),
288 emitc::OpaqueAttr::get(b.getContext(),
289 foldDDRAddrOffset ? "true" : "false"));
290 Value argPlus = ap.getArgPlus();
291 // i32 offsets are unsigned bit patterns in the static emitter.
292 // Cast before widening so bit 31 is not sign-extended to 64 bits.
293 if (argPlus.getType().isInteger(32))
294 argPlus = emitc::CastOp::create(b, loc, getU32Type(b.getContext()),
295 argPlus);
296 emitTxnCall(b, loc, "txn_append_arg_patch", txnVec,
297 {addrV, idxV, argPlus, foldV});
298 countOp(b, loc, count);
299 })
300 .Case<AIEX::NpuBlockWriteOp>([&](auto bw) {
301 convertBlockWrite(b, loc, bw);
302 countOp(b, loc, count);
303 })
304 .Case<AIEX::NpuBlockWriteValuesOp>([&](auto bw) {
305 convertBlockWriteValues(b, loc, bw);
306 countOp(b, loc, count);
307 })
308 .Case<cf::AssertOp>([&](auto a) {
309 // Host-side guard: a violated condition yields no stream
310 // (std::nullopt), and its message is what the host reports. Appends
311 // nothing, so not counted.
312 emitc::VerbatimOp::create(
313 b, loc, "if (!({})) " + refuse(a.getMsg(), /*inFormat=*/true),
314 ValueRange{a.getArg()});
315 })
316 .Case<AIEX::DMABdPoolPopOp>([&](AIEX::DMABdPoolPopOp pop) {
317 if (std::optional<uint32_t> id = pop.getId()) {
318 emitc::VerbatimOp::create(b, loc,
319 "aie_runtime::bd_pool_reserve(" +
320 bdPoolName(pop) + ", " +
321 std::to_string(*id) + ");");
322 pop.getBdId().replaceAllUsesWith(emitc::LiteralOp::create(
323 b, loc, pop.getBdId().getType(), std::to_string(*id)));
324 return;
325 }
326 // Draw a BD id from the tile's runtime pool (declared in the
327 // prologue) into a fresh C++ variable; nullopt if the pool is empty.
328 // Downstream ops consume the id, so replace the SSA result with a
329 // literal naming the variable.
330 std::string var = "bd_" + std::to_string(nextPoolVar++);
331 emitc::VerbatimOp::create(
332 b, loc,
333 "uint32_t " + var + "; if (!aie_runtime::bd_pool_pop(" +
334 bdPoolName(pop) + ", " + var + ")) " +
335 refuse("no free buffer descriptor on tile (" +
336 std::to_string(pop.getColumn()) + ", " +
337 std::to_string(pop.getRow()) +
338 "): the sequence keeps more transfers in flight "
339 "than the tile has descriptors",
340 /*inFormat=*/false));
341 Value ref =
342 emitc::LiteralOp::create(b, loc, pop.getBdId().getType(), var);
343 pop.getBdId().replaceAllUsesWith(ref);
344 })
345 .Case<AIEX::DMABdPoolPushOp>([&](AIEX::DMABdPoolPushOp push) {
346 // Return a BD id to the tile's runtime pool.
347 emitc::CallOpaqueOp::create(
348 b, loc, TypeRange{}, "aie_runtime::bd_pool_push",
349 ValueRange{poolRef(b, loc, bdPoolName(push)), push.getBdId()});
350 })
351 // XRT allocates the scratchpad only for a full-ELF context, which has
352 // no per-call instruction buffer to carry a generated stream.
353 .Case<AIEX::NpuCreateScratchpadOp, AIEX::NpuUpdateFromScratchpadOp>(
354 [&](Operation *sp) {
355 fail(sp, "needs the scratchpad of a full-ELF context, which the "
356 "C++ TXN target's per-call streams run without; use a "
357 "runtime sequence argument instead of a scratchpad "
358 "parameter");
359 })
360 // memref.get_global feeding a blockwrite is consumed by
361 // convertBlockWrite (data inlined); the now-dead op is erased later.
362 .Case<memref::GetGlobalOp>([&](auto) {})
363 .Default([&](Operation *unsupported) {
364 if (isa<scf::SCFDialect>(unsupported->getDialect()))
365 fail(unsupported,
366 "control flow in runtime sequences is not yet supported by "
367 "the C++ TXN target");
368 else
369 fail(unsupported, "is not supported by the C++ TXN target");
370 });
371 }
372
373 // The compile-time-resolved absolute address (folding buffer/col/row) as a
374 // uint32_t literal, or null if it could not be resolved statically. Address
375 // resolution depends on the parent device, so it is precomputed before the op
376 // is cloned out (see recordDeviceResolved).
377 Value resolvedAddr(OpBuilder &b, Location loc, Operation *clone) {
378 auto it = resolved.absoluteAddr.find(clone);
379 if (it == resolved.absoluteAddr.end())
380 return {};
381 return u32Literal(b, loc, it->second);
382 }
383
384 // The address for a write32/maskwrite32: the device-resolved literal, else a
385 // genuine runtime address (arith-derived, e.g. the pool's bdBase + wordIdx).
386 // A bare block argument selects no register and is rejected; null for a
387 // symbolic/unresolved address.
388 Value runtimeOrResolvedAddr(OpBuilder &b, Location loc, Operation *clone,
389 Value addrOperand) {
390 if (Value lit = resolvedAddr(b, loc, clone))
391 return lit;
392 Operation *def = addrOperand ? addrOperand.getDefiningOp() : nullptr;
393 if (def && !isa<arith::ConstantOp>(def))
394 return addrOperand;
395 return {};
396 }
397
398 // Emit a diagnostic on `op` and mark the conversion failed.
399 void fail(Operation *op, const llvm::Twine &msg) {
400 op->emitOpError(msg);
401 ok = false;
402 }
403
404 // An emitc.literal referencing a pool variable (for pass-by-reference into
405 // bd_pool_push).
406 Value poolRef(OpBuilder &b, Location loc, StringRef name) {
407 return emitc::LiteralOp::create(
408 b, loc, emitc::OpaqueType::get(b.getContext(), "aie_runtime::BdPool"),
409 name);
410 }
411
412 void convertBlockWrite(OpBuilder &b, Location loc, AIEX::NpuBlockWriteOp bw) {
413 auto addrIt = resolved.absoluteAddr.find(bw);
414 auto dataIt = resolved.blockWriteData.find(bw);
415 if (addrIt == resolved.absoluteAddr.end() ||
416 dataIt == resolved.blockWriteData.end() || !dataIt->second) {
417 bw.emitOpError("cannot convert blockwrite without a constant address and "
418 "data to the C++ TXN target");
419 ok = false;
420 return;
421 }
422 uint32_t addr = addrIt->second;
423 DenseIntElementsAttr data = dataIt->second;
424
425 // Emit the payload as a typed EmitC array variable rather than a verbatim
426 // C++ string, so the generated code carries real types.
427 MLIRContext *ctx = b.getContext();
428 int64_t n = data.size();
429 auto arrTy =
430 emitc::ArrayType::get(ctx, SmallVector<int64_t>{n}, getU32Type(ctx));
431 std::string init = "{";
432 llvm::raw_string_ostream ss(init);
433 bool first = true;
434 for (APInt word : data.getValues<APInt>()) {
435 if (!first)
436 ss << ", ";
437 ss << llvm::format("0x%08xu", static_cast<unsigned>(word.getZExtValue()));
438 first = false;
439 }
440 ss << "}";
441 auto arrVar = emitc::VariableOp::create(b, loc, arrTy,
442 emitc::OpaqueAttr::get(ctx, init));
443
444 uint32_t colVal = 0, rowVal = 0;
445 if (auto col = bw.getColumn(), row = bw.getRow(); col && row) {
446 colVal = *col;
447 rowVal = *row;
448 }
449 emitTxnCall(b, loc, "txn_append_blockwrite", txnVec,
450 {u32Literal(b, loc, addr), arrVar.getResult(),
451 u32Literal(b, loc, static_cast<uint32_t>(n)),
452 u32Literal(b, loc, colVal), u32Literal(b, loc, rowVal)});
453 }
454
455 // A blockwrite whose payload is computed at TXN-build time:
456 // stage the words into a local C++ array, then hand that array
457 // to one txn_append_blockwrite. Unlike convertBlockWrite there is no constant
458 // memref to inline, so the slots are filled by assignment from the operand
459 // values, which convert-arith-to-emitc lowers in place afterwards.
460 void convertBlockWriteValues(OpBuilder &b, Location loc,
461 AIEX::NpuBlockWriteValuesOp bw) {
462 MLIRContext *ctx = b.getContext();
463 Value addrV = runtimeOrResolvedAddr(b, loc, bw, bw.getAddress());
464 if (!addrV) {
465 fail(bw, "cannot convert a symbolic/unresolved blockwrite_values address "
466 "to the C++ TXN target");
467 return;
468 }
469 ValueRange words = bw.getValues();
470 int64_t n = static_cast<int64_t>(words.size());
471
472 // Declare the staging array (zero-initialized; every slot is assigned
473 // below). Typed emitc.variable, matching convertBlockWrite's array.
474 auto arrTy =
475 emitc::ArrayType::get(ctx, SmallVector<int64_t>{n}, getU32Type(ctx));
476 auto arrVar = emitc::VariableOp::create(b, loc, arrTy,
477 emitc::OpaqueAttr::get(ctx, "{}"));
478
479 // Fill the slots. Emitted as verbatim assignments (the same mechanism the
480 // runtime guards above use to reference a not-yet-lowered SSA value): the
481 // i32 words convert to the array's uint32_t elementwise, which is the
482 // intended two's-complement reinterpretation of the packed BD fields.
483 for (int64_t i = 0; i < n; i++)
484 emitc::VerbatimOp::create(b, loc, "{}[" + std::to_string(i) + "] = {};",
485 ValueRange{arrVar.getResult(), words[i]});
486
487 // col/row are 0: the address is already flat (as for npu.blockwrite).
488 emitTxnCall(b, loc, "txn_append_blockwrite", txnVec,
489 {addrV, arrVar.getResult(),
490 u32Literal(b, loc, static_cast<uint32_t>(n)),
491 u32Literal(b, loc, 0), u32Literal(b, loc, 0)});
492 }
493
494 emitc::FuncOp funcOp;
495 Value txnVec;
496 const DeviceResolved &resolved;
497 // Runtime op-count variable (the C++ `__opcount`), or null when the sequence
498 // is straight-line and the count is a compile-time literal.
499 Value opCountVar;
500 bool ok = true;
501 // Counter for unique popped-BD-id C++ variable names.
502 unsigned nextPoolVar = 0;
503 bool foldDDRAddrOffset;
504};
505
506struct ConvertAIEXToEmitCPass
507 : xilinx::impl::ConvertAIEXToEmitCBase<ConvertAIEXToEmitCPass> {
508 ConvertAIEXToEmitCPass() = default;
509 // foldDDRAddrOffset is `protected` on the generated base, settable only via
510 // a -pass-pipeline string; this constructor is the programmatic equivalent.
511 explicit ConvertAIEXToEmitCPass(const ConvertAIEXToEmitCOptions &options)
512 : ConvertAIEXToEmitCBase(options) {}
513
514 void runOnOperation() override {
515 ModuleOp moduleOp = getOperation();
516 MLIRContext *ctx = &getContext();
517 if (failed(AIE::inlineWriteConfigs(moduleOp)))
518 return signalPassFailure();
519
520 struct SeqInfo {
521 AIE::RuntimeSequenceOp seq;
522 AIE::DeviceOp device;
523 };
524 SmallVector<SeqInfo> sequences;
525 moduleOp.walk([&](AIE::RuntimeSequenceOp seq) {
526 sequences.push_back({seq, seq->getParentOfType<AIE::DeviceOp>()});
527 });
528 if (emitDispatchShim && sequences.size() != 1) {
529 moduleOp.emitOpError()
530 << "emit-dispatch-shim needs exactly one aie.runtime_sequence to "
531 "wrap, found "
532 << sequences.size();
533 return signalPassFailure();
534 }
535 if (sequences.empty())
536 return;
537
538 OpBuilder builder(ctx);
539 for (auto &[seqOp, deviceOp] : sequences) {
540 if (!deviceOp) {
541 seqOp.emitOpError("must be nested inside an aie.device");
542 return signalPassFailure();
543 }
544 std::optional<emitc::FuncOp> gen =
545 emitFunction(builder, moduleOp, seqOp, deviceOp);
546 if (!gen)
547 return signalPassFailure();
548 if (emitDispatchShim) {
549 emitc::FuncOp generated = *gen;
550 if (failed(emitDispatchShimFuncs(builder, moduleOp, generated)))
551 return signalPassFailure();
552 }
553 }
554
555 // Replace the module body with just the generated emitc funcs + includes.
556 SmallVector<Operation *> toErase;
557 for (Operation &op : *moduleOp.getBody())
558 if (!isa<emitc::FuncOp, emitc::IncludeOp>(op))
559 toErase.push_back(&op);
560 for (Operation *op : llvm::reverse(toErase))
561 op->erase();
562
563 // Lower the arith ops (constant scalar fields, runtime-value arithmetic
564 // feeding npu ops) and any scf control flow (a rolled dynamic loop) left in
565 // the function bodies to emitc.
566 if (failed(lowerArithAndScfToEmitC(moduleOp)))
567 return signalPassFailure();
568
569 builder.setInsertionPointToStart(moduleOp.getBody());
570 emitc::IncludeOp::create(builder, moduleOp.getLoc(),
571 "aie/Runtime/TxnEncoding.h",
572 /*is_standard_include=*/false);
573 emitc::IncludeOp::create(builder, moduleOp.getLoc(), "cstdint",
574 /*is_standard_include=*/true);
575 emitc::IncludeOp::create(builder, moduleOp.getLoc(), "vector",
576 /*is_standard_include=*/true);
577 // The builder returns std::optional: a runtime scalar that would overflow a
578 // narrow BD field yields std::nullopt instead of a truncated stream.
579 emitc::IncludeOp::create(builder, moduleOp.getLoc(), "optional",
580 /*is_standard_include=*/true);
581 }
582
583 // Run the upstream arith-to-emitc and scf-to-emitc conversions over the
584 // generated functions in one pass: a rolled dynamic loop is scf.for, and its
585 // bounds / iter_args are arith, so both must lower together.
586 LogicalResult lowerArithAndScfToEmitC(ModuleOp moduleOp) {
587 // ArithToEmitC has no patterns for the integer ops the Python bindings
588 // emit for `//`, ceildiv, min and max on staged scalars. Expand them to
589 // the divsi/cmpi/select forms it does lower before converting.
590 {
591 RewritePatternSet expand(moduleOp.getContext());
592 arith::populateCeilFloorDivExpandOpsPatterns(expand);
593 arith::populateExpandMinMaxIPatterns(expand);
594 // Rewrite only: folding or CSE here would reshape the sequence the
595 // per-op conversion below expects (and the C++ its tests check).
596 GreedyRewriteConfig config;
597 config.enableFolding(false).enableConstantCSE(false);
598 if (failed(applyPatternsGreedily(moduleOp, std::move(expand), config)))
599 return failure();
600 }
601
602 TypeConverter typeConverter;
603 typeConverter.addConversion([](Type t) { return t; });
604 populateEmitCSizeTTypeConversions(typeConverter);
605
606 RewritePatternSet patterns(moduleOp.getContext());
607 populateArithToEmitCPatterns(typeConverter, patterns);
608 populateSCFToEmitCConversionPatterns(patterns, typeConverter);
609
610 ConversionTarget target(*moduleOp.getContext());
611 target.addLegalDialect<emitc::EmitCDialect>();
612 target.addIllegalDialect<arith::ArithDialect>();
613 target.addIllegalDialect<scf::SCFDialect>();
614 return applyPartialConversion(moduleOp, target, std::move(patterns));
615 }
616
617private:
618 // The C spelling emitc's translator emits for a parameter type, for the ABI
619 // string only. Must mirror CppEmitter::emitType down to its signedness rule,
620 // or the reported ABI disagrees with the emitted signature.
621 static std::optional<std::string> cTypeName(Type t) {
622 if (isa<emitc::SizeTType>(t))
623 return std::string("size_t");
624 auto intTy = dyn_cast<IntegerType>(t);
625 if (!intTy || !emitc::isSupportedIntegerType(intTy))
626 return std::nullopt;
627 if (intTy.getWidth() == 1)
628 return std::string("bool");
629 return (intTy.isUnsigned() ? "uint" : "int") +
630 std::to_string(intTy.getWidth()) + "_t";
631 }
632
633 // Emit the ctypes-callable entry points: dispatch_abi() reporting the
634 // parameter types, and dispatch_generate() handing back a pointer + word
635 // count into thread-local storage, or -2 when the builder declined.
636 LogicalResult emitDispatchShimFuncs(OpBuilder &builder, ModuleOp moduleOp,
637 emitc::FuncOp gen) {
638 MLIRContext *ctx = moduleOp.getContext();
639 Location loc = gen.getLoc();
640 TypeRange genParams = gen.getFunctionType().getInputs();
641
642 SmallVector<std::string> abiTypes;
643 for (Type t : genParams) {
644 std::optional<std::string> name = cTypeName(t);
645 if (!name)
646 return gen.emitOpError()
647 << "runtime-sequence parameter type " << t
648 << " has no dispatch ABI spelling; it cannot be passed from the "
649 "host at dispatch time";
650 abiTypes.push_back(*name);
651 }
652
653 builder.setInsertionPointToEnd(moduleOp.getBody());
654 // Python resolves these two by name out of the built shared library. ELF
655 // exports every extern symbol unless told otherwise, but MSVC-target
656 // linking exports nothing without an explicit marker, so on Windows the
657 // DLL would load and then fail to resolve dispatch_abi. The macro comes
658 // from TxnEncoding.h, which the emitted file already includes, and expands
659 // to nothing off Windows.
660 auto externC =
661 builder.getStrArrayAttr({"extern \"C\"", "AIE_DISPATCH_EXPORT"});
662
663 // Pointers must be emitc.ptr: an opaque type may not have a pointer as its
664 // outer type.
665 auto charPtrTy =
666 emitc::PointerType::get(emitc::OpaqueType::get(ctx, "const char"));
667 auto abiFn = emitc::FuncOp::create(builder, loc, "dispatch_abi",
668 FunctionType::get(ctx, {}, {charPtrTy}));
669 abiFn.setSpecifiersAttr(externC);
670 OpBuilder ab = OpBuilder::atBlockBegin(abiFn.addEntryBlock());
671 Value abiStr = emitc::LiteralOp::create(
672 ab, loc, charPtrTy, "\"" + llvm::join(abiTypes, ",") + "\"");
673 emitc::ReturnOp::create(ab, loc, abiStr);
674
675 SmallVector<Type> shimParams(genParams);
676 shimParams.push_back(
677 emitc::PointerType::get(emitc::PointerType::get(getU32Type(ctx))));
678 auto i64Ty = emitc::OpaqueType::get(ctx, "int64_t");
679 auto shimFn =
680 emitc::FuncOp::create(builder, loc, "dispatch_generate",
681 FunctionType::get(ctx, shimParams, {i64Ty}));
682 shimFn.setSpecifiersAttr(externC);
683 Block *shimBlock = shimFn.addEntryBlock();
684 OpBuilder sb = OpBuilder::atBlockBegin(shimBlock);
685
686 SmallVector<Value> genArgs(shimBlock->getArguments().drop_back());
687 SmallVector<StringRef> holes(genArgs.size(), "{}");
688 std::string call = "auto __result = " + gen.getSymName().str() + "(" +
689 llvm::join(holes, ", ") + ");";
690 emitc::VerbatimOp::create(
691 sb, loc, "static thread_local " + kTxnVecType.str() + " __txn;");
692 emitc::VerbatimOp::create(sb, loc, "aie_runtime::txn_refusal = nullptr;");
693 emitc::VerbatimOp::create(sb, loc, call, genArgs);
694 emitc::VerbatimOp::create(sb, loc, "if (!__result) return -2;");
695 emitc::VerbatimOp::create(sb, loc, "__txn = std::move(*__result);");
696 emitc::VerbatimOp::create(sb, loc, "*{} = __txn.data();",
697 ValueRange{shimBlock->getArguments().back()});
698 emitc::ReturnOp::create(
699 sb, loc,
700 emitc::LiteralOp::create(sb, loc, i64Ty,
701 "static_cast<int64_t>(__txn.size())"));
702
703 // dispatch_last_refusal(): why the last dispatch_generate() on this
704 // thread returned -2 (a string literal in this library), or null.
705 auto whyFn = emitc::FuncOp::create(builder, loc, "dispatch_last_refusal",
706 FunctionType::get(ctx, {}, {charPtrTy}));
707 whyFn.setSpecifiersAttr(externC);
708 OpBuilder wb = OpBuilder::atBlockBegin(whyFn.addEntryBlock());
709 emitc::ReturnOp::create(
710 wb, loc,
711 emitc::LiteralOp::create(wb, loc, charPtrTy,
712 "aie_runtime::txn_refusal"));
713 return success();
714 }
715
716 // Resolve `orig`'s device-dependent values (still under the device) keyed by
717 // its detached `clone`.
718 static void recordDeviceResolved(Operation *orig, Operation *clone,
719 DeviceResolved &resolved) {
720 if (auto w = dyn_cast<AIEX::NpuWrite32Op>(orig)) {
721 if (auto a = w.getAbsoluteAddress())
722 resolved.absoluteAddr[clone] = *a;
723 } else if (auto mw = dyn_cast<AIEX::NpuMaskWrite32Op>(orig)) {
724 if (auto a = mw.getAbsoluteAddress())
725 resolved.absoluteAddr[clone] = *a;
726 } else if (auto mp = dyn_cast<AIEX::NpuMaskPollOp>(orig)) {
727 if (auto a = mp.getAbsoluteAddress())
728 resolved.absoluteAddr[clone] = *a;
729 } else if (auto bw = dyn_cast<AIEX::NpuBlockWriteOp>(orig)) {
730 if (auto a = bw.getAbsoluteAddress())
731 resolved.absoluteAddr[clone] = *a;
732 if (auto d = bw.getDataWords())
733 resolved.blockWriteData[clone] = d;
734 } else if (auto bwv = dyn_cast<AIEX::NpuBlockWriteValuesOp>(orig)) {
735 // Already absolute: no buffer/col/row to fold in.
736 if (auto a = AIEX::getConstantIntOperand(bwv.getAddress()))
737 resolved.absoluteAddr[clone] = *a;
738 }
739 }
740
741 FailureOr<emitc::FuncOp> emitFunction(OpBuilder &builder, ModuleOp moduleOp,
742 AIE::RuntimeSequenceOp seqOp,
743 AIE::DeviceOp deviceOp) {
744 Location loc = seqOp.getLoc();
745 Block &entry = seqOp.getBody().front();
746
747 // The generated function takes the sequence's non-memref args (the runtime
748 // scalars) and returns the assembled txn vector. Memref args address host
749 // buffers resolved by address_patch; they are not function parameters here.
750 SmallVector<Type> paramTypes;
751 auto txnVecType =
752 emitc::OpaqueType::get(moduleOp.getContext(), kTxnVecType);
753 // The builder can fail at TXN-build time (a runtime scalar overflowing a
754 // narrow BD field), so it returns std::optional<std::vector<uint32_t>>:
755 // std::nullopt on a failed guard, the assembled vector otherwise.
756 auto txnRetType = emitc::OpaqueType::get(
757 moduleOp.getContext(),
758 (llvm::Twine("std::optional<") + kTxnVecType + ">").str());
759 // A runtime scalar of type `index` (e.g. a loop trip count) has no C++
760 // spelling on its own; emit it as emitc.size_t so it flows straight into a
761 // converted scf.for bound with no leftover cast. Other scalar types pass
762 // through unchanged.
763 auto sizeT = emitc::SizeTType::get(moduleOp.getContext());
764 auto paramTypeFor = [&](Type t) -> Type {
765 return isa<IndexType>(t) ? Type(sizeT) : t;
766 };
767 for (BlockArgument arg : entry.getArguments())
768 if (!isa<BaseMemRefType>(arg.getType()))
769 paramTypes.push_back(paramTypeFor(arg.getType()));
770
771 builder.setInsertionPointToEnd(moduleOp.getBody());
772 std::string funcName = "generate_txn_" + deviceOp.getSymName().str() + "_" +
773 seqOp.getSymName().str();
774 auto funcOp = emitc::FuncOp::create(
775 builder, loc, funcName,
776 FunctionType::get(moduleOp.getContext(), paramTypes,
777 TypeRange{txnRetType}));
778 funcOp.setSpecifiersAttr(builder.getStrArrayAttr({"inline"}));
779 Block *funcBlock = funcOp.addEntryBlock();
780 OpBuilder fb = OpBuilder::atBlockBegin(funcBlock);
781
782 // EmitC has no native std::vector construction, so declare the accumulator
783 // with a verbatim statement and reference it by name via an emitc.literal
784 // (which translates inline, no extra copy). All txn_append_* calls take
785 // this value, so the generated C++ operates on the single `txn` vector.
786 emitc::VerbatimOp::create(fb, loc, "std::vector<uint32_t> txn;");
787 Value txnVec = emitc::LiteralOp::create(fb, loc, txnVecType, "txn");
788 emitTxnCall(fb, loc, "txn_init", txnVec, {});
789
790 // Declare each runtime BD free-list pool the sequence draws ids from,
791 // with the bounds its ops name.
792 llvm::StringSet<> declaredPools;
793 auto declarePool = [&](auto poolOp) {
794 std::string name = bdPoolName(poolOp);
795 if (!declaredPools.insert(name).second)
796 return;
797 uint32_t lo = poolOp.getBdBegin(), hi = poolOp.getBdEnd();
798 emitc::VerbatimOp::create(fb, loc,
799 "aie_runtime::BdPool " + name +
800 " = aie_runtime::bd_pool_init_range(" +
801 std::to_string(lo) + ", " +
802 std::to_string(hi) + ");");
803 };
804 seqOp.walk([&](Operation *op) {
805 if (auto pop = dyn_cast<AIEX::DMABdPoolPopOp>(op))
806 declarePool(pop);
807 else if (auto push = dyn_cast<AIEX::DMABdPoolPushOp>(op))
808 declarePool(push);
809 });
810
811 // A rolled loop makes the op count a runtime quantity: declare a __opcount
812 // accumulator the converter bumps per op. A straight-line sequence keeps
813 // the compile-time literal count (byte-identical golden).
814 bool hasControlFlow = false;
815 seqOp.walk([&](Operation *op) {
816 if (isa<scf::SCFDialect>(op->getDialect()))
817 hasControlFlow = true;
818 });
819 Value opCountVar;
820 if (hasControlFlow) {
821 emitc::VerbatimOp::create(fb, loc, "uint32_t __opcount = 0;");
822 opCountVar = emitc::LiteralOp::create(
823 fb, loc, getU32Type(moduleOp.getContext()), "__opcount");
824 }
825
826 // Clone the sequence body (whole regions, so a rolled scf.for comes along),
827 // mapping non-memref block args to function params. Resolve device-relative
828 // values (address, blockwrite data) while the originals are still under the
829 // device, keyed by clone, since the accessors don't work once detached.
830 IRMapping mapping;
831 unsigned p = 0;
832 for (BlockArgument arg : entry.getArguments())
833 if (!isa<BaseMemRefType>(arg.getType()))
834 mapping.map(arg, funcBlock->getArgument(p++));
835 DeviceResolved resolved;
836 for (Operation &op : entry.without_terminator()) {
837 fb.clone(op, mapping);
838 // Record device-resolved values for the clone and any nested op (a BD
839 // inside a rolled loop resolves the same way as a top-level one).
840 op.walk([&](Operation *orig) {
841 Operation *c = mapping.lookupOrNull(orig);
842 if (c)
843 recordDeviceResolved(orig, c, resolved);
844 });
845 }
846
847 AIEXToEmitCConverter conv(funcOp, txnVec, resolved, opCountVar,
848 foldDDRAddrOffset);
849 std::optional<uint32_t> count = conv.run();
850 if (!count)
851 return failure();
852
853 // Finalize the header with the op count + device info. The count is the
854 // runtime `__opcount` when the sequence has a loop, else the compile-time
855 // literal.
856 const AIE::AIETargetModel &tm = deviceOp.getTargetModel();
857 OpBuilder eb(funcBlock, funcBlock->end());
858 std::string countStr =
859 hasControlFlow ? "__opcount" : (std::to_string(*count) + "u");
860 // txn_device_info assigns TxnDeviceInfo by field name, so a field added or
861 // reordered there cannot silently mis-encode this generated header.
862 std::string header = "aie_runtime::txn_prepend_header(txn, " + countStr +
863 ", aie_runtime::txn_device_info(" +
864 std::to_string(AIE::txnDeviceGen(tm)) + ", " +
865 std::to_string(tm.rows()) + ", " +
866 std::to_string(tm.columns()) + ", " +
867 std::to_string(tm.getNumMemTileRows()) + "));";
868 emitc::VerbatimOp::create(eb, loc, header);
869 // Return the vector as the optional result. The literal text differs from
870 // the "txn" accumulator literal (so the two are not deduplicated) and is
871 // typed as the optional return so emitc's return-type check passes; it
872 // relies on the implicit std::vector -> std::optional conversion in C++.
873 Value ret = emitc::LiteralOp::create(eb, loc, txnRetType, "std::move(txn)");
874 emitc::ReturnOp::create(eb, loc, ret);
875 return funcOp;
876 }
877};
878
879} // namespace
880
881std::unique_ptr<OperationPass<ModuleOp>>
883 return std::make_unique<ConvertAIEXToEmitCPass>();
884}
885
886std::unique_ptr<OperationPass<ModuleOp>>
888 bool emitDispatchShim) {
889 ConvertAIEXToEmitCOptions options;
890 options.foldDDRAddrOffset = foldDDRAddrOffset;
891 options.emitDispatchShim = emitDispatchShim;
892 return std::make_unique<ConvertAIEXToEmitCPass>(options);
893}
virtual int rows() const =0
Return the number of rows in the device.
virtual int columns() const =0
Return the number of columns in the device.
virtual uint32_t getNumMemTileRows() const =0
std::optional< uint32_t > getConstantIntOperand(mlir::Value v)
uint8_t txnDeviceGen(const AIETargetModel &tm)
Device generation ID written into the TXN header (aie_runtime::TxnDeviceInfo::devGen).
mlir::LogicalResult inlineWriteConfigs(mlir::ModuleOp module)
std::unique_ptr< mlir::OperationPass< mlir::ModuleOp > > createConvertAIEXToEmitCPass()