290 AIE::TileOp &tile,
int channel,
291 AIE::DMAChannelDir channelDir,
293 OpFoldResult lengthField) {
295 auto buf = bd_op.getBuffer();
296 auto col = tile.getCol();
297 auto row = tile.getRow();
301 return bd_op->emitOpError(
"has no buffer descriptor layout on this tile");
302 bool channelLocalIds =
307 auto constBdId = bdId ? getConstantIntValue(bdId) : std::nullopt;
308 uint32_t placeholderId =
314 constBdId ? *constBdId : bd_op.getBdId().value_or(placeholderId);
315 uint64_t register_addr =
320 std::optional<uint64_t> staticByteAddress;
325 Value runtimeRegisterAddr;
326 if (bdId && !getConstantIntValue(bdId)) {
328 row, bdId, channel, channelDir);
329 runtimeRegisterAddr = arith::AddIOp::create(
330 builder, bd_op.getLoc(), base,
339 if (bd_op.getOffsetStateTableIdxAttr() && runtimeRegisterAddr)
340 return bd_op->emitOpError(
341 "offset_state_table_idx is not supported with a runtime bd_id; the "
342 "scratchpad update targets a compile-time BD register address.");
348 mlir::BlockArgument buf_arg =
nullptr;
351 if (
auto directArg = llvm::dyn_cast<mlir::BlockArgument>(buf)) {
355 buf_arg = traceResult->rootArg;
356 offset = traceResult->offsetInBytes;
360 if (!target_model.
isShimNOCTile(tile.getCol(), tile.getRow())) {
361 return bd_op->emitOpError(
"DDR memory (runtime input arguments) can "
362 "only be referred to on shim tiles.");
367 return bd_op->emitOpError(
368 "buffer must resolve to a memref argument of the runtime sequence");
369 unsigned arg_idx = *hostIdx;
374 OpFoldResult offsetOfr =
375 bd_op.getOffset() ? OpFoldResult(bd_op.getOffset())
376 : OpFoldResult(builder.getI32IntegerAttr(
377 bd_op.getConstantOffset().value_or(0)));
378 OpFoldResult oneStride = builder.getI32IntegerAttr(1);
381 bd_op.getBufferElementTypeWidthInBytes(), offset,
385 NpuAddressPatchOp::create(builder, bd_op.getLoc(),
389 }
else if (AIE::BufferOp buffer =
390 llvm::dyn_cast<AIE::BufferOp>(buf.getDefiningOp())) {
391 std::optional<uint32_t> bufferAddr = buffer.getAddress();
392 if (!bufferAddr.has_value()) {
393 return bd_op->emitOpError(
394 "Cannot lower buffer without associated address. Run pass "
395 "--aie-assign-buffer-addresses first or manually assign an "
398 uint64_t buf_addr = *bufferAddr;
401 int memCol = buffer.getTileOp().getCol();
402 int memRow = buffer.getTileOp().getRow();
403 std::optional<uint32_t> addrOffset =
406 return bd_op->emitOpError(
"the memory of tile (")
407 << memCol <<
", " << memRow
408 <<
") is not reachable from the DMA of memtile (" << col
409 <<
", " << row <<
")";
410 buf_addr += *addrOffset;
415 uint64_t maxByteAddr = (uint64_t(addrBits.
mask()) + 1) * divisor - 1;
416 if (buf_addr > maxByteAddr)
417 return bd_op->emitOpError(
"buffer address exceeds the tile's DMA "
422 bool constOffset = !bd_op.getOffset() || bd_op.getConstantOffset();
423 Location loc = bd_op.getLoc();
426 buf_addr += bd_op.getOffsetInBytes();
427 if (buf_addr > maxByteAddr)
428 return bd_op->emitOpError(
"buffer address exceeds the tile's DMA "
430 staticByteAddress = buf_addr;
436 {OpFoldResult(builder.getI32IntegerAttr(1))},
437 bd_op.getBufferElementTypeWidthInBytes(),
438 (int64_t)buf_addr, divisor);
441 Type i64 = builder.getI64Type();
442 Value fits = builder.createOrFold<arith::CmpIOp>(
443 loc, arith::CmpIPredicate::ule, byteAddr,
444 arith::ConstantOp::create(builder, loc,
445 IntegerAttr::get(i64, maxByteAddr)));
447 "a runtime DMA offset puts the buffer "
448 "address past the tile's DMA address "
452 byteAddr = arith::DivUIOp::create(
453 builder, loc, byteAddr,
454 arith::ConstantOp::create(builder, loc,
455 IntegerAttr::get(i64, divisor)));
456 addrField = arith::TruncIOp::create(builder, loc, builder.getI32Type(),
458 if (addrBits.
shift != 0)
459 addrField = arith::ShLIOp::create(
460 builder, loc, addrField,
467 ? runtimeRegisterAddr
469 static_cast<uint32_t
>(register_addr));
470 uint32_t addrMask = addrBits.
place(0xFFFFFFFF);
471 if (addrMask == 0xFFFFFFFF)
472 NpuWrite32Op::create(builder, loc, regAddrVal, addrField,
nullptr,
475 NpuMaskWrite32Op::create(builder, loc, regAddrVal, addrField,
477 nullptr,
nullptr,
nullptr);
479 return bd_op->emitOpError(
480 "Buffer argument must be a constant aie.buffer, a runtime sequence "
481 "input argument, or a supported chain of memref.subview, "
482 "memref.view, memref.cast, or memref.reinterpret_cast operations "
483 "rooted at a block argument. Subviews must be static and contiguous; "
484 "views must have a constant byte shift and no dynamic result sizes.");
493 if (bd_op.getOffsetStateTableIdxAttr()) {
494 auto bufType = llvm::cast<BaseMemRefType>(bd_op.getBuffer().getType());
496 builder, bd_op, bufType, register_addr, target_model, col, row,
497 staticByteAddress, lengthField)))
510 std::optional<xilinx::AIE::PacketInfoAttr> packet,
511 bool outOfOrder =
false) {
516 if (std::optional<uint32_t> nextBdId = bd_op.getNextBdId()) {
525 auto info = bd_op.getPacket().value_or(packet.value_or(
nullptr));
527 if (!info.isAssigned()) {
528 bd_op.emitOpError(
"packet has no pkt_id; allocation assigns one, so a "
529 "header at this level must carry it");
533 tile.getRow(), info.getPktType())))
540 if (std::optional<int32_t> oooId = bd_op.getOutOfOrderId())
543 if (std::optional<AIE::BDIterationAttr> iter = bd_op.getIteration())
548 auto lockValue = [&](AIE::UseLockOp op, int32_t &constOut,
549 Value &valueOut) -> LogicalResult {
550 if (std::optional<int64_t> c = getConstantIntValue(op.getValue())) {
551 constOut = op.acquireGE() ? -
static_cast<int32_t
>(*c)
552 :
static_cast<int32_t
>(*c);
555 Location loc = op.getLoc();
556 int32_t minValue = op.acquireGE() ? 1 : 0;
558 Value fromMin = builder.createOrFold<arith::SubIOp>(
560 Value inRange = builder.createOrFold<arith::CmpIOp>(
561 loc, arith::CmpIPredicate::ule, fromMin,
564 "a runtime lock value must be in [" +
565 Twine(minValue) +
":" + Twine(maxValue) +
568 valueOut = op.getValue();
570 valueOut = arith::SubIOp::create(
575 AIE::UseLockOp acquire_op, release_op;
581 auto lockIdFor = [&](AIE::LockOp lock, int32_t id) -> FailureOr<int32_t> {
582 if (!target_model.
isMemTile(tile.getCol(), tile.getRow()))
585 tile.getCol(), tile.getRow(), lock.colIndex(), lock.rowIndex());
587 bd_op.emitOpError(
"the locks of tile (")
588 << lock.colIndex() <<
", " << lock.rowIndex()
589 <<
") are not reachable from the DMA of memtile (" << tile.getCol()
590 <<
", " << tile.getRow() <<
")";
593 return id +
static_cast<int32_t
>(*offset);
596 AIE::LockOp rel_lock = release_op.getLockOp();
600 AIE::LockOp acq_lock = acquire_op.getLockOp();
601 if (std::optional<int32_t> acqLockId = acq_lock.getLockID()) {
602 FailureOr<int32_t>
id = lockIdFor(acq_lock, *acqLockId);
613 if (std::optional<int32_t> relLockId = rel_lock.getLockID()) {
614 FailureOr<int32_t>
id = lockIdFor(rel_lock, *relLockId);
635 AIE::TileOp &tile,
int channel,
636 AIE::DMAChannelDir channelDir,
637 std::optional<xilinx::AIE::PacketInfoAttr> packet,
638 Value runtimeBdId =
nullptr,
bool outOfOrder =
false) {
640 Location loc = bd_op.getLoc();
641 int col = tile.getCol();
642 int row = tile.getRow();
645 target_model, packet, outOfOrder);
646 if (failed(fieldsOr))
656 OpFoldResult bdIdOfr;
658 bdIdOfr = runtimeBdId;
660 std::optional<uint32_t> staticBdId = bd_op.getBdId();
661 assert(staticBdId &&
"static bd_id must be assigned (checked by "
662 "verifyBdInBlock before lowering)");
663 bdIdOfr = builder.getI32IntegerAttr(*staticBdId);
672 SmallVector<OpFoldResult> sizes(bd_op.getMixedSizes());
673 SmallVector<OpFoldResult> strides(bd_op.getMixedStrides());
674 if (sizes.size() > 4 || strides.size() > 4)
675 return bd_op->emitOpError(
676 "At most four data layout transformation dimensions may be "
677 "provided; aie-decompose-large-dma-bd splits a longer one.");
678 OpFoldResult one = builder.getI64IntegerAttr(1);
679 OpFoldResult zeroOfr = builder.getI64IntegerAttr(0);
680 SmallVector<OpFoldResult, 4> sizes4(4, one), strides4(4, zeroOfr);
682 strides4.back() = one;
683 for (
size_t i = 0; i < sizes.size(); i++) {
684 sizes4[4 - sizes.size() + i] = sizes[i];
685 strides4[4 - strides.size() + i] = strides[i];
689 if (std::optional<AIE::BDIterationAttr> iter = bd_op.getIteration()) {
690 sizes4.front() = builder.getI64IntegerAttr(iter->getSize());
691 strides4.front() = builder.getI64IntegerAttr(iter->getStride());
699 if (Value lenOperand = bd_op.getLen())
701 else if (std::optional<int32_t> constLen = bd_op.getConstantLen())
702 lenOfr = builder.getI32IntegerAttr(*constLen);
703 else if (bd_op.getSizes().empty() && bd_op.getStrides().empty()) {
704 auto bufTy = cast<BaseMemRefType>(bd_op.getBuffer().getType());
705 if (!bufTy.hasStaticShape() ||
706 (bd_op.getOffset() && !bd_op.getConstantOffset()))
707 return bd_op->emitOpError(
708 "runtime-valued BD requires an explicit transfer length; provide a "
709 "`len` for this buffer descriptor.");
710 lenOfr = builder.getI64IntegerAttr(bufTy.getNumElements());
715 std::optional<int64_t> constLen =
716 lenOfr ? getConstantIntValue(lenOfr) : std::nullopt;
717 std::optional<int64_t> dimsLen = 1;
718 for (OpFoldResult s : llvm::drop_begin(sizes4)) {
719 std::optional<int64_t> c = getConstantIntValue(s);
727 static_cast<uint64_t
>(bd_op.getBufferElementTypeWidthInBytes()) * 8;
728 if (!sizes.empty() && constLen && dimsLen && *dimsLen != *constLen) {
729 auto err = bd_op->emitOpError(
730 "Buffer descriptor length does not match length of "
731 "transfer expressed by lowest three dimensions of data "
732 "layout transformation strides/wraps. ")
733 <<
"BD length is " << (*constLen * elemWidth / 8)
734 <<
" bytes. Lowest three dimensions of data layout "
735 "transformation would result in transfer of "
736 << (*dimsLen * elemWidth / 8) <<
" bytes. ";
737 err.attachNote() <<
"Do not include the highest dimension size in "
738 "transfer length, as this is the BD repeat count.";
749 (lenOfr && isConstantIntValue(strides4[3], 1) &&
750 llvm::all_of(ArrayRef(sizes4).drop_back(),
751 [](OpFoldResult v) {
return isConstantIntValue(v, 1); }));
760 SmallVector<Value> bdWords;
763 builder, loc, target_model, col, row, f, sizes4, strides4,
764 elemWidth, bd_op.getBurstLength(), bd_op.getAxcacheOrDefault(),
765 linear ? OpFoldResult() : lenOfr, bdRepeatCount, bdWords)))
770 OpFoldResult offsetOfr =
771 bd_op.getOffset() ? OpFoldResult(bd_op.getOffset())
772 : OpFoldResult(builder.getI32IntegerAttr(
773 bd_op.getConstantOffset().value_or(0)));
775 builder, loc, cast<BaseMemRefType>(trace->rootArg.getType()),
776 trace->offsetInBytes, elemWidth / 8, {offsetOfr}, {one}, sizes4,
783 bdIdOfr, channel, channelDir);
784 NpuBlockWriteValuesOp::create(builder, loc, bdBase, bdWords);
786 target_model.getDmaBdLayout(col, row, channelDir);
788 builder, bd_op, tile, channel, channelDir, bdIdOfr,
795 int channel, AIE::DMAChannelDir channelDir,
796 std::optional<xilinx::AIE::PacketInfoAttr> packet,
797 bool outOfOrder =
false) {
799 Value runtimeBdId = bd_op.getBdIdVal();
802 tile.getRow(), channelDir)))
805 if (std::optional<uint32_t>
id = bd_op.getBdId();
806 id && target_model.hasChannelLocalBdIds(tile.getCol(), tile.getRow()) &&
807 !target_model.isBdChannelAccessible(tile.getCol(), tile.getRow(), *
id,
808 channel, channelDir))
809 return bd_op->emitOpError(
"BD ID ")
810 << *
id <<
" is not in the BD pool of "
811 << AIE::stringifyDMAChannelDir(channelDir) <<
" channel "
813 auto buffer_type = llvm::cast<BaseMemRefType>(bd_op.getBuffer().getType());
814 uint32_t addr_granularity = target_model.getAddressGenGranularity();
824 bool runtimeLen = bd_op.getLen() && !bd_op.getConstantLen();
825 bool runtimeOffset = bd_op.getOffset() && !bd_op.getConstantOffset();
827 llvm::any_of(bd_op.getMixedSizes(),
828 [](OpFoldResult s) { return !getConstantIntValue(s); }) ||
829 llvm::any_of(bd_op.getMixedStrides(),
830 [](OpFoldResult s) { return !getConstantIntValue(s); });
833 llvm::any_of(block.getOps<AIE::UseLockOp>(), [](AIE::UseLockOp op) {
834 return !getConstantIntValue(op.getValue());
836 if (runtimeLen || runtimeDims || runtimeOffset || runtimeBdId ||
837 runtimeNextBd || runtimeLock) {
841 if (bd_op.getLengthStateTableIdxAttr())
842 return bd_op->emitOpError(
"length_parameter requires a constant "
843 "offset, bd_id, next_bd and lock value");
844 int col = tile.getCol(), row = tile.getRow();
845 if (!target_model.isShimNOCTile(col, row) &&
846 !target_model.isMemTile(col, row) &&
847 !target_model.isCoreTile(col, row))
848 return bd_op->emitOpError(
849 "runtime-valued BD size/stride/len/bd_id/next_bd/lock value is "
850 "only supported on tiles with a DMA buffer descriptor layout (shim "
852 "core tiles); use compile-time constants here.");
853 if (bd_op.getPadDimensions().has_value())
854 return bd_op->emitOpError(
855 "zero padding is not supported with runtime sizes/strides/len.");
860 static_cast<uint64_t
>(bd_op.getBufferElementTypeWidthInBytes()) * 8;
861 SmallVector<OpFoldResult, 4> sizesRev(
862 llvm::reverse(bd_op.getMixedSizes()));
863 SmallVector<OpFoldResult, 4> stridesRev(
864 llvm::reverse(bd_op.getMixedStrides()));
866 bd_op, sizesRev, stridesRev, elemWidth,
867 target_model.getAddressGenGranularity())))
870 channelDir, packet, runtimeBdId,
879 std::optional<uint32_t> bdIdAttr = bd_op.getBdId();
880 assert(bdIdAttr &&
"static bd_id must be assigned (checked by "
881 "verifyBdInBlock before lowering)");
882 uint32_t bd_id = *bdIdAttr;
883 int64_t offset = bd_op.getOffsetInBytes();
884 uint64_t len = bd_op.getLenInBytes();
885 uint64_t len_addr_granularity = len * 8 / addr_granularity;
887 if (offset * 8 % addr_granularity != 0) {
888 return bd_op->emitOpError(
"Offset must be aligned to ")
889 << (addr_granularity / 8) <<
" byte boundary.";
893 if (len < addr_granularity / 8 && !bd_op.getLengthStateTableIdxAttr()) {
894 return bd_op->emitOpError(
"Transfer size of ")
895 << len <<
" bytes falls below minimum hardware transfer unit of "
896 << (addr_granularity / 8) <<
" bytes.";
899 std::optional<llvm::SmallVector<AIE::BDDimLayoutAttr>> dimsStorage =
900 bd_op.getConstantDimensions();
902 return bd_op->emitOpError(
"internal error folding BD dimensions");
905 std::optional<AIE::BDIterationAttr> iter = bd_op.getIteration();
906 if (iter && dimsStorage->empty())
907 dimsStorage->push_back(AIE::BDDimLayoutAttr::get(
908 builder.getContext(), len / bd_op.getBufferElementTypeWidthInBytes(),
910 std::optional<llvm::ArrayRef<AIE::BDDimLayoutAttr>> dims;
911 if (!dimsStorage->empty())
912 dims = llvm::ArrayRef<AIE::BDDimLayoutAttr>(*dimsStorage);
913 llvm::SmallVector<int64_t, 4> sizes = llvm::SmallVector<int64_t, 4>(4, 0);
914 llvm::SmallVector<int64_t, 4> strides = llvm::SmallVector<int64_t, 4>(4, 0);
917 std::optional<llvm::ArrayRef<AIE::BDPadLayoutAttr>> padDims =
918 bd_op.getPadDimensions();
919 llvm::SmallVector<int64_t, 4> padBefore =
920 llvm::SmallVector<int64_t, 4>(4, 0);
921 llvm::SmallVector<int64_t, 4> padAfter =
922 llvm::SmallVector<int64_t, 4>(4, 0);
923 llvm::fill(padBefore, 0);
924 llvm::fill(padAfter, 0);
932 auto iteration_size = 0;
933 auto iteration_stride = 0;
935 if (dims && !dims->empty()) {
936 llvm::SmallVector<int64_t, 4> input_sizes =
937 llvm::SmallVector<int64_t, 4>(4, 1);
938 llvm::SmallVector<int64_t, 4> input_strides =
939 llvm::SmallVector<int64_t, 4>(4, 0);
940 if (dims->size() > 4) {
941 return bd_op->emitOpError(
942 "At most four data layout transformation dimensions may be "
943 "provided; aie-decompose-large-dma-bd splits a longer one.");
946 for (
size_t i = 0; i < dims->size(); i++) {
950 int j = dims->size() - i - 1;
951 input_sizes[i] = (*dims)[j].getSize();
952 input_strides[i] = (*dims)[j].getStride();
955 input_sizes[3] = iter->getSize();
956 input_strides[3] = iter->getStride();
966 !padDims.has_value() &&
968 input_sizes, input_strides);
969 if (!treatAsLinear && bd_op.getLengthStateTableIdxAttr())
972 if (padDims.has_value()) {
974 target_model.getDmaBdLayout(tile.getCol(), tile.getRow());
975 size_t numPadFields = layout ? layout->
padFields().size() : 0;
976 if (numPadFields == 0)
977 return bd_op->emitOpError()
978 <<
"Padding is only supported by memtile dma bds.";
979 if (padDims->size() > dims->size())
980 return bd_op->emitOpError()
981 <<
"Mismatch number of dimensions between padding(s)"
982 <<
" and wrap(s) and stride(s).";
983 for (
auto [d, pad] : llvm::enumerate(llvm::reverse(*padDims)))
984 if (d >= numPadFields &&
985 (pad.getConstPadBefore() || pad.getConstPadAfter()))
986 return bd_op->emitOpError()
988 <<
" zero padding is not supported on this tile.";
989 if (channelDir == AIE::DMAChannelDir::MM2S) {
990 for (
size_t i = 0; i < padDims->size(); i++) {
991 int j = padDims->size() - i - 1;
992 padBefore[i] = (*padDims)[j].getConstPadBefore();
993 padAfter[i] = (*padDims)[j].getConstPadAfter();
995 for (
size_t i = padDims->size(); i < dims->size(); i++) {
999 int64_t elementBytes = bd_op.getBufferElementTypeWidthInBytes();
1000 if ((padBefore[0] * elementBytes) % 4 ||
1001 (padAfter[0] * elementBytes) % 4)
1002 return bd_op->emitOpError()
1003 <<
"Inner-most padding count must result in padding in "
1005 padBefore[0] = padBefore[0] * elementBytes / 4;
1006 padAfter[0] = padAfter[0] * elementBytes / 4;
1008 return bd_op->emitOpError()
1009 <<
"supports padding only for MM2S direction on MemTiles.";
1012 buffer_type, input_sizes, input_strides, sizes,
1016 bd_op, [&] {
return bd_op->emitOpError(); }, buffer_type,
1017 tile.getCol(), tile.getRow(), input_sizes, input_strides, sizes,
1018 strides, treatAsLinear))) {
1022 iteration_size = sizes[3];
1023 iteration_stride = strides[3];
1025 if (!treatAsLinear) {
1028 d0stride = strides[0];
1032 d1stride = strides[1];
1035 d2stride = strides[2];
1040 d2size = (target_model.isMemTile(tile.getCol(), tile.getRow()))
1044 if (input_sizes[3] > 1 && input_strides[3] == 0) {
1050 iteration_stride = 0;
1057 uint64_t len_dims_addr_granularity = 1;
1058 for (
size_t i = 0; i < 3; i++) {
1059 len_dims_addr_granularity *= sizes[i] + padBefore[i] + padAfter[i];
1062 bool runtimeLengthFromZero =
1063 len_addr_granularity == 0 && bd_op.getLengthStateTableIdxAttr();
1064 if (len_dims_addr_granularity != len_addr_granularity &&
1065 !runtimeLengthFromZero) {
1068 "Buffer descriptor length does not match length of transfer "
1069 "expressed by lowest three dimensions of data layout "
1070 "transformation strides/wraps. ")
1071 <<
"BD length is " << (len_addr_granularity * addr_granularity / 8)
1073 <<
"Lowest three dimensions of data layout transformation would "
1074 "result in transfer of "
1075 << (len_dims_addr_granularity * addr_granularity / 8) <<
" bytes. ";
1076 err.attachNote() <<
"Do not include the highest dimension size in "
1077 "transfer length, as this is the BD repeat count.";
1081 if (padDims && target_model.isMemTile(tile.getCol(), tile.getRow()) &&
1082 channelDir == AIE::DMAChannelDir::MM2S) {
1083 return bd_op->emitOpError()
1084 <<
"Padding requires n-d data layouts expressed as "
1085 <<
"wrap(s) and stride(s).";
1088 return bd_op->emitOpError()
1089 <<
" Padding is supported only on MemTiles.";
1093 target_model, packet, outOfOrder);
1094 if (failed(fieldsOr))
1096 bool channelLocalIds = target_model.usesChannelLocalBdIds(
1097 tile.getCol(), tile.getRow(), channelDir);
1101 NpuWriteBdOp::create(
1102 builder, bd_op.getLoc(), tile.getCol(), bd_id, len_addr_granularity,
1122 padBefore[1], padBefore[2],
1123 padAfter[0], padAfter[1],
1125 bd_op.getBurstLength(),
1127 target_model.isShimNOCTile(tile.getCol(), tile.getRow())
1128 ? builder.getI32IntegerAttr(bd_op.getAxcacheOrDefault())
1131 channelLocalIds ? builder.getI32IntegerAttr(channel) : IntegerAttr(),
1133 ? AIE::DMAChannelDirAttr::get(builder.getContext(), channelDir)
1134 : AIE::DMAChannelDirAttr());
1136 builder, bd_op, tile, channel, channelDir, {},
1137 builder.getI64IntegerAttr(len_addr_granularity))))
1143 auto lengthUnit = bd_op.getLengthUnit();
1144 if (bd_op.getLengthStateTableIdxAttr() && lengthUnit)
1146 builder, bd_op, buffer_type, *lengthUnit, target_model, tile.getCol(),
1147 tile.getRow(), bd_id);