22#include "mlir/IR/BuiltinTypes.h"
23#include "mlir/IR/ImplicitLocOpBuilder.h"
30#define GEN_PASS_DEF_ESICONNECTSERVICES
31#include "circt/Dialect/ESI/ESIPasses.h.inc"
45 ServiceDeclOpInterface,
46 ServiceImplRecordOp implRecord) {
47 auto *ctxt = implReq.getContext();
49 Value clk = implReq.getOperand(0);
50 Value rst = implReq.getOperand(1);
52 if (implReq.getImplOpts()) {
53 auto opts = implReq.getImplOpts()->getValue();
54 for (
auto nameAttr : opts) {
55 return implReq.emitOpError(
"did not recognize option name ")
56 << nameAttr.getName();
60 Block &connImplBlock = implRecord.getReqDetails().front();
61 implRecord.setIsEngine(
true);
62 OpBuilder implRecords = OpBuilder::atBlockEnd(&connImplBlock);
65 auto toStringAttr = [&](ArrayAttr strArr, StringAttr channelName) {
67 llvm::raw_string_ostream os(buff);
69 strArr.getAsRange<AppIDAttr>(), os,
70 [&](AppIDAttr appid) {
71 os << appid.getName().getValue();
73 os <<
"[" << appid.getIndex() <<
"]";
76 os <<
"." << channelName.getValue();
77 return StringAttr::get(ctxt, os.str());
80 auto getAssignment = [&](StringAttr name, StringAttr channelName) {
81 DictionaryAttr assignment = b.getDictionaryAttr({
82 b.getNamedAttr(
"type", b.getStringAttr(
"cosim")),
83 b.getNamedAttr(
"name", channelName),
85 return b.getNamedAttr(name, assignment);
88 llvm::DenseMap<ServiceImplementConnReqOp, unsigned> toClientResultNum;
89 for (
auto req : implReq.getOps<ServiceImplementConnReqOp>())
90 toClientResultNum[req] = toClientResultNum.size();
97 for (
auto req : implReq.getOps<ServiceImplementConnReqOp>()) {
98 Location loc = req->getLoc();
99 ChannelBundleType bundleType = req.getToClient().getType();
100 SmallVector<NamedAttribute, 8> channelAssignments;
102 SmallVector<Value, 8> toServerValues;
104 if (ch.direction == ChannelDirection::to) {
105 auto cosim = b.create<CosimFromHostEndpointOp>(
106 loc, ch.type, clk, rst,
107 toStringAttr(req.getRelativeAppIDPathAttr(), ch.name));
108 toServerValues.push_back(cosim.getFromHost());
109 channelAssignments.push_back(getAssignment(ch.name, cosim.getIdAttr()));
114 b.create<PackBundleOp>(implReq.getLoc(), bundleType, toServerValues);
115 implReq.getResult(toClientResultNum[req])
116 .replaceAllUsesWith(pack.getBundle());
120 if (ch.direction == ChannelDirection::from) {
121 auto cosim = b.create<CosimToHostEndpointOp>(
122 loc, clk, rst, pack.getFromChannels()[chanIdx++],
123 toStringAttr(req.getRelativeAppIDPathAttr(), ch.name));
124 channelAssignments.push_back(getAssignment(ch.name, cosim.getIdAttr()));
128 implRecords.create<ServiceImplClientRecordOp>(
129 req.getLoc(), req.getRelativeAppIDPathAttr(), req.getServicePortAttr(),
130 TypeAttr::get(bundleType), b.getDictionaryAttr(channelAssignments),
143 ServiceDeclOpInterface decl,
144 ServiceImplRecordOp) {
146 return implReq.emitOpError(
147 "Must specify a service declaration to use 'sv_mem'.");
149 ImplicitLocOpBuilder b(implReq.getLoc(), implReq);
152 RandomAccessMemoryDeclOp ramDecl =
153 dyn_cast<RandomAccessMemoryDeclOp>(decl.getOperation());
155 return implReq.emitOpError(
156 "'sv_mem' implementation type can only be used to "
157 "implement RandomAccessMemory declarations");
159 if (implReq.getNumOperands() != 2)
160 return implReq.emitOpError(
"Implementation requires clk and rst operands");
161 auto clk = implReq.getOperand(0);
162 auto rst = implReq.getOperand(1);
163 auto write = b.getStringAttr(
"write");
164 auto read = b.getStringAttr(
"read");
166 APInt( 0, 0,
false));
167 auto i1 = b.getI1Type();
171 SmallVector<ServiceImplementConnReqOp, 8> toClientReqs(
172 llvm::make_filter_range(
173 implReq.getOps<ServiceImplementConnReqOp>(),
174 [](
auto req) { return req.getToClient() != nullptr; }));
177 DenseMap<Value, Value> outputMap;
178 for (
auto [bout, reqout] :
179 llvm::zip_longest(toClientReqs, implReq.getResults())) {
181 assert(reqout.has_value());
182 Value toClient = bout->getToClient();
183 outputMap[toClient] = *reqout;
187 hw::UnpackedArrayType memType =
188 hw::UnpackedArrayType::get(ramDecl.getInnerType(), ramDecl.getDepth());
190 b.create<
sv::RegOp>(memType, implReq.getServiceSymbolAttr().getAttr())
195 SmallVector<std::tuple<Value, Value, Value>> writeGoAddressData;
196 for (
auto req : implReq.getOps<ServiceImplementConnReqOp>()) {
197 auto port = req.getServicePort().getName();
204 auto doneValid = bb.
get(i1);
205 auto ackChannel = b.create<WrapValidReadyOp>(none, doneValid);
208 b.create<PackBundleOp>(implReq.getLoc(), req.getToClient().getType(),
209 ackChannel.getChanOutput());
211 pack.getFromChannels()[RandomAccessMemoryDeclOp::ReqDirChannelIdx];
212 toClientResp = pack.getBundle();
216 b.create<UnwrapValidReadyOp>(toServer, ackChannel.getReady());
219 b.getStringAttr(
"address"));
221 b.getStringAttr(
"data"));
225 go->setAttr(
"sv.namehint", b.getStringAttr(
"write_go"));
230 writeGoAddressData.push_back(std::make_tuple(go, address, data));
232 }
else if (port == read) {
236 auto dataValid = bb.
get(i1);
237 auto data = bb.
get(ramDecl.getInnerType());
238 auto dataChannel = b.create<WrapValidReadyOp>(data, dataValid);
241 b.create<PackBundleOp>(implReq.getLoc(), req.getToClient().getType(),
242 dataChannel.getChanOutput());
244 pack.getFromChannels()[RandomAccessMemoryDeclOp::RespDirChannelIdx];
245 toClientResp = pack.getBundle();
249 b.create<UnwrapValidReadyOp>(toServer, dataChannel.getReady());
251 b.create<sv::ArrayIndexInOutOp>(mem, addressUnwrap.getRawOutput());
255 data.setValue(readData);
256 dataValid.setValue(addressUnwrap.getValid());
258 assert(
false &&
"Port should be either 'read' or 'write'");
261 outputMap[req.getToClient()].replaceAllUsesWith(toClientResp);
265 auto hwClk = b.create<seq::FromClockOp>(clk);
266 b.create<sv::AlwaysFFOp>(
267 sv::EventControl::AtPosEdge, hwClk, sv::ResetType::SyncReset,
268 sv::EventControl::AtPosEdge, rst, [&] {
269 for (
auto [go, address, data] : writeGoAddressData) {
270 Value a = address, d = data;
272 b.create<sv::IfOp>(go, [&] {
273 Value memLoc = b.create<sv::ArrayIndexInOutOp>(mem, a);
274 b.create<sv::PAssignOp>(memLoc, d);
289 ServiceDeclOpInterface decl) {
292 auto genF =
genLookupTable.find(req.getImplTypeAttr().getValue());
295 return req.emitOpError(
"Could not find service generator for attribute '")
296 << req.getImplTypeAttr() <<
"'";
303 auto implRecord = b.create<ServiceImplRecordOp>(
304 req.getLoc(), req.getAppID(),
false,
305 req.getServiceSymbolAttr(), req.getStdServiceAttr(),
306 req.getImplTypeAttr(), b.getDictionaryAttr({}));
307 implRecord.getReqDetails().emplaceBlock();
309 return genF->second(req, decl, implRecord);
313 DenseMap<StringRef, ServiceGeneratorDispatcher::ServiceGeneratorFunc>{
319 return ::globalDispatcher;
341 DenseMap<Operation *, SmallVector<igraph::InstanceOpInterface, 1>>
342 moduleInstantiations;
344 void getAndSortModules(ModuleOp topMod,
345 SmallVectorImpl<hw::HWModuleLike> &mods);
346 void getAndSortModulesVisitor(hw::HWModuleLike mod,
347 SmallVectorImpl<hw::HWModuleLike> &mods,
348 DenseSet<Operation *> &modsSeen);
352void ModuleSorter::getAndSortModules(ModuleOp topMod,
353 SmallVectorImpl<hw::HWModuleLike> &mods) {
355 DenseSet<Operation *> modsSeen;
357 moduleInstantiations.clear();
358 topMod.walk([&](hw::HWModuleLike mod) {
359 getAndSortModulesVisitor(mod, mods, modsSeen);
364void ModuleSorter::getAndSortModulesVisitor(
365 hw::HWModuleLike mod, SmallVectorImpl<hw::HWModuleLike> &mods,
366 DenseSet<Operation *> &modsSeen) {
367 if (modsSeen.contains(mod))
369 modsSeen.insert(mod);
371 mod.walk([&](igraph::InstanceOpInterface inst) {
372 auto targetNameAttrs = inst.getReferencedModuleNamesAttr();
373 for (
auto targetNameAttr : targetNameAttrs) {
375 topLevelSyms.getDefinition(cast<StringAttr>(targetNameAttr));
377 moduleInstantiations[modOp].push_back(inst);
378 if (
auto modLike = dyn_cast<hw::HWModuleLike>(modOp))
379 getAndSortModulesVisitor(modLike, mods, modsSeen);
389struct ESIConnectServicesPass
390 :
public circt::esi::impl::ESIConnectServicesBase<ESIConnectServicesPass>,
394 : genDispatcher(gen) {}
395 ESIConnectServicesPass()
398 void runOnOperation()
override;
403 void convertReq(RequestConnectionOp);
408 LogicalResult surfaceReqs(hw::HWMutableModuleLike,
409 ArrayRef<ServiceImplementConnReqOp>);
414 LogicalResult replaceInst(ServiceInstanceOp,
415 ArrayRef<ServiceImplementConnReqOp> portReqs);
419 LogicalResult process(hw::HWModuleLike);
422 StringAttr getStdService(FlatSymbolRefAttr serviceSym);
429void ESIConnectServicesPass::runOnOperation() {
430 ModuleOp outerMod = getOperation();
431 topLevelSyms.addDefinitions(outerMod);
433 outerMod.walk([&](RequestConnectionOp req) { convertReq(req); });
439 SmallVector<hw::HWModuleLike, 64> sortedMods;
440 getAndSortModules(outerMod, sortedMods);
443 for (
auto mod : sortedMods) {
444 hw::HWModuleLike mutableMod = dyn_cast<hw::HWModuleLike>(*mod);
445 if (mutableMod && failed(process(mutableMod))) {
453StringAttr ESIConnectServicesPass::getStdService(FlatSymbolRefAttr svcSym) {
456 Operation *svcDecl = topLevelSyms.getDefinition(svcSym);
457 if (!isa<CustomServiceDeclOp>(svcDecl))
458 return svcDecl->getName().getIdentifier();
462void ESIConnectServicesPass::convertReq(RequestConnectionOp req) {
464 auto newReq = b.create<ServiceImplementConnReqOp>(
465 req.getLoc(), req.getToClient().getType(), req.getServicePortAttr(),
466 ArrayAttr::get(&getContext(), {req.getAppIDAttr()}));
467 newReq->setDialectAttrs(req->getDialectAttrs());
468 req.getToClient().replaceAllUsesWith(newReq.getToClient());
471 b.create<ServiceRequestRecordOp>(
472 req.getLoc(), req.getAppID(), req.getServicePortAttr(),
473 getStdService(req.getServicePortAttr().getModuleRef()),
474 req.getToClient().getType());
478LogicalResult ESIConnectServicesPass::process(hw::HWModuleLike mod) {
480 if (mod->getNumRegions() == 0 || mod->getRegion(0).empty())
483 Block &modBlock = mod->getRegion(0).front();
486 SetVector<ServiceImplementConnReqOp> nonLocalReqs;
488 llvm::MapVector<SymbolRefAttr, llvm::SetVector<ServiceImplementConnReqOp>>
490 for (
auto instOp : modBlock.getOps<ServiceInstanceOp>())
491 localImplReqs[instOp.getServiceSymbolAttr()] = {};
495 llvm::SetVector<ServiceImplementConnReqOp> *anyServiceInst =
nullptr;
496 if (
auto defaultService = localImplReqs.find(SymbolRefAttr());
497 defaultService != localImplReqs.end())
498 anyServiceInst = &defaultService->second;
500 auto sortConnReqs = [&]() {
502 for (
auto req :
llvm::make_early_inc_range(
503 mod.
getBodyBlock()->getOps<ServiceImplementConnReqOp>())) {
504 auto service = req.getServicePort().getModuleRef();
505 auto reqListIter = localImplReqs.find(service);
506 if (reqListIter != localImplReqs.end())
507 reqListIter->second.insert(req);
508 else if (anyServiceInst)
509 anyServiceInst->insert(req);
511 nonLocalReqs.insert(req);
520 llvm::make_early_inc_range(modBlock.getOps<ServiceInstanceOp>())) {
521 auto portReqs = localImplReqs[instOp.getServiceSymbolAttr()];
522 if (failed(replaceInst(instOp, portReqs.getArrayRef())))
526 for (RequestConnectionOp req :
llvm::make_early_inc_range(
533 if (nonLocalReqs.empty())
536 if (
auto mutableMod = dyn_cast<hw::HWMutableModuleLike>(mod.getOperation()))
537 return surfaceReqs(mutableMod, nonLocalReqs.getArrayRef());
538 return mod.emitOpError(
539 "Cannot surface requests through module without mutable ports");
542LogicalResult ESIConnectServicesPass::replaceInst(
543 ServiceInstanceOp instOp, ArrayRef<ServiceImplementConnReqOp> portReqs) {
544 auto declSym = instOp.getServiceSymbolAttr();
545 ServiceDeclOpInterface decl;
547 decl = dyn_cast_or_null<ServiceDeclOpInterface>(
548 topLevelSyms.getDefinition(declSym));
550 return instOp.emitOpError(
"Could not find service declaration ")
556 SmallVector<Type, 8> resultTypes(instOp.getResultTypes().begin(),
557 instOp.getResultTypes().end());
558 for (
auto req : portReqs)
559 resultTypes.push_back(req.getBundleType());
563 auto implOp = b.create<ServiceImplementReqOp>(
564 instOp.getLoc(), resultTypes, instOp.getAppIDAttr(),
565 instOp.getServiceSymbolAttr(), instOp.getImplTypeAttr(),
566 getStdService(declSym), instOp.getImplOptsAttr(), instOp.getOperands());
567 implOp->setDialectAttrs(instOp->getDialectAttrs());
568 Block &reqBlock = implOp.getPortReqs().emplaceBlock();
571 for (
auto [n, o] :
llvm::zip(implOp.getResults(), instOp.getResults()))
572 o.replaceAllUsesWith(n);
573 unsigned instOpNumResults = instOp.getNumResults();
574 for (
size_t idx = 0, e = portReqs.size(); idx < e; ++idx) {
575 ServiceImplementConnReqOp req = portReqs[idx];
576 req.getToClient().replaceAllUsesWith(
577 implOp.getResult(idx + instOpNumResults));
580 for (
auto req : portReqs)
581 req->moveBefore(&reqBlock, reqBlock.
end());
589 if (failed(genDispatcher.generate(implOp, decl)))
590 return implOp.emitOpError(
"failed to generate server");
596ESIConnectServicesPass::surfaceReqs(hw::HWMutableModuleLike mod,
597 ArrayRef<ServiceImplementConnReqOp> reqs) {
598 auto *
ctxt = mod.getContext();
599 Block *body = &mod->getRegion(0).front();
602 unsigned origNumInputs = mod.getNumInputPorts();
603 SmallVector<std::pair<unsigned, hw::PortInfo>> newInputs;
606 auto getPortName = [&](ArrayAttr namePath) {
607 std::string portName;
608 llvm::raw_string_ostream nameOS(portName);
610 namePath.getAsRange<AppIDAttr>(), nameOS,
611 [&](AppIDAttr appid) {
612 nameOS << appid.getName().getValue();
613 if (appid.getIndex())
614 nameOS <<
"_" << appid.getIndex();
617 return StringAttr::get(ctxt, nameOS.str());
620 for (
auto req : reqs)
621 if (req->getParentWithTrait<
OpTrait::IsIsolatedFromAbove>() != mod)
622 return req.emitOpError(
623 "Cannot surface requests through isolated from above ops");
626 for (
auto req : reqs) {
627 newInputs.push_back(std::make_pair(
629 hw::PortInfo{{getPortName(req.getRelativeAppIDPathAttr()),
636 Value replValue = body->addArgument(req.getBundleType(), req->getLoc());
637 req.getToClient().replaceAllUsesWith(replValue);
639 mod.insertPorts(newInputs, {});
642 auto prependNamePart = [&](ArrayAttr appIDPath, AppIDAttr appID) {
643 SmallVector<Attribute, 8> newAppIDPath;
644 newAppIDPath.push_back(appID);
645 newAppIDPath.append(appIDPath.begin(), appIDPath.end());
646 return ArrayAttr::get(appIDPath.getContext(), newAppIDPath);
650 SmallVector<igraph::InstanceOpInterface, 1> newModuleInstantiations;
651 for (
auto inst : moduleInstantiations[mod]) {
655 SmallVector<Value, 16> newOperands;
656 for (
auto req : reqs) {
658 ArrayAttr appIDPath = req.getRelativeAppIDPathAttr();
659 if (
auto instAppID = dyn_cast_or_null<AppIDAttr>(
660 inst->getDiscardableAttr(AppIDAttr::AppIDAttrName)))
661 appIDPath = prependNamePart(appIDPath, instAppID);
664 auto clone = b.create<ServiceImplementConnReqOp>(
665 req.getLoc(), req.getToClient().getType(), req.getServicePortAttr(),
667 clone->setDialectAttrs(req->getDialectAttrs());
668 newOperands.push_back(clone.getToClient());
670 inst->insertOperands(inst->getNumOperands(), newOperands);
672 if (
auto hwInst = dyn_cast<hw::InstanceOp>(*inst))
673 hwInst.setArgNamesAttr(b.getArrayAttr(mod.getInputNames()));
678 for (
auto req : reqs)
683std::unique_ptr<OperationPass<ModuleOp>>
685 return std::make_unique<ESIConnectServicesPass>();
assert(baseType &&"element must be base type")
static ServiceGeneratorDispatcher globalDispatcher(DenseMap< StringRef, ServiceGeneratorDispatcher::ServiceGeneratorFunc >{ {"cosim", instantiateCosimEndpointOps}, {"sv_mem", instantiateSystemVerilogMemory}}, false)
static LogicalResult instantiateCosimEndpointOps(ServiceImplementReqOp implReq, ServiceDeclOpInterface, ServiceImplRecordOp implRecord)
The generator for the "cosim" impl_type.
static LogicalResult instantiateSystemVerilogMemory(ServiceImplementReqOp implReq, ServiceDeclOpInterface decl, ServiceImplRecordOp)
static EvaluatorValuePtr unwrap(OMEvaluatorValue c)
static Block * getBodyBlock(FModuleLike mod)
Instantiate one of these and use it to build typed backedges.
Backedge get(mlir::Type resultType, mlir::LocationAttr optionalLoc={})
Create a typed backedge.
Default symbol cache implementation; stores associations between names (StringAttr's) to mlir::Operat...
Class which "dispatches" a service implementation request to its specified generator.
void registerGenerator(StringRef implType, ServiceGeneratorFunc gen)
Add a generator to this registry.
LogicalResult generate(ServiceImplementReqOp, ServiceDeclOpInterface)
Generate a service implementation if a generator exists in this registry.
static ServiceGeneratorDispatcher & globalDispatcher()
Get the global dispatcher.
DenseMap< StringRef, ServiceGeneratorFunc > genLookupTable
std::function< LogicalResult(ServiceImplementReqOp, ServiceDeclOpInterface, ServiceImplRecordOp)> ServiceGeneratorFunc
std::unique_ptr< OperationPass< ModuleOp > > createESIConnectServicesPass()
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
This holds the name, type, direction of a module's ports.