CIRCT 20.0.0git
Loading...
Searching...
No Matches
ESIServices.cpp
Go to the documentation of this file.
1//===- ESIServices.cpp - Code related to ESI services ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "PassDetails.h"
10
21
22#include "mlir/IR/BuiltinTypes.h"
23#include "mlir/IR/ImplicitLocOpBuilder.h"
24
25#include <memory>
26#include <utility>
27
28namespace circt {
29namespace esi {
30#define GEN_PASS_DEF_ESICONNECTSERVICES
31#include "circt/Dialect/ESI/ESIPasses.h.inc"
32} // namespace esi
33} // namespace circt
34
35using namespace circt;
36using namespace circt::esi;
37
38//===----------------------------------------------------------------------===//
39// C++ service generators.
40//===----------------------------------------------------------------------===//
41
42/// The generator for the "cosim" impl_type.
43static LogicalResult
44instantiateCosimEndpointOps(ServiceImplementReqOp implReq,
45 ServiceDeclOpInterface,
46 ServiceImplRecordOp implRecord) {
47 auto *ctxt = implReq.getContext();
48 OpBuilder b(implReq);
49 Value clk = implReq.getOperand(0);
50 Value rst = implReq.getOperand(1);
51
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();
57 }
58 }
59
60 Block &connImplBlock = implRecord.getReqDetails().front();
61 implRecord.setIsEngine(true);
62 OpBuilder implRecords = OpBuilder::atBlockEnd(&connImplBlock);
63
64 // Assemble the name to use for an endpoint.
65 auto toStringAttr = [&](ArrayAttr strArr, StringAttr channelName) {
66 std::string buff;
67 llvm::raw_string_ostream os(buff);
68 llvm::interleave(
69 strArr.getAsRange<AppIDAttr>(), os,
70 [&](AppIDAttr appid) {
71 os << appid.getName().getValue();
72 if (appid.getIndex())
73 os << "[" << appid.getIndex() << "]";
74 },
75 ".");
76 os << "." << channelName.getValue();
77 return StringAttr::get(ctxt, os.str());
78 };
79
80 auto getAssignment = [&](StringAttr name, StringAttr channelName) {
81 DictionaryAttr assignment = b.getDictionaryAttr({
82 b.getNamedAttr("type", b.getStringAttr("cosim")),
83 b.getNamedAttr("name", channelName),
84 });
85 return b.getNamedAttr(name, assignment);
86 };
87
88 llvm::DenseMap<ServiceImplementConnReqOp, unsigned> toClientResultNum;
89 for (auto req : implReq.getOps<ServiceImplementConnReqOp>())
90 toClientResultNum[req] = toClientResultNum.size();
91
92 // Iterate through the requests, building a cosim endpoint for each channel in
93 // the bundle.
94 // TODO: The cosim op should probably be able to take a bundle type and get
95 // lowered to the SV primitive later on. The SV primitive will also need some
96 // work to suit this new world order, so let's put this off.
97 for (auto req : implReq.getOps<ServiceImplementConnReqOp>()) {
98 Location loc = req->getLoc();
99 ChannelBundleType bundleType = req.getToClient().getType();
100 SmallVector<NamedAttribute, 8> channelAssignments;
101
102 SmallVector<Value, 8> toServerValues;
103 for (BundledChannel ch : bundleType.getChannels()) {
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()));
110 }
111 }
112
113 auto pack =
114 b.create<PackBundleOp>(implReq.getLoc(), bundleType, toServerValues);
115 implReq.getResult(toClientResultNum[req])
116 .replaceAllUsesWith(pack.getBundle());
117
118 size_t chanIdx = 0;
119 for (BundledChannel ch : bundleType.getChannels()) {
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()));
125 }
126 }
127
128 implRecords.create<ServiceImplClientRecordOp>(
129 req.getLoc(), req.getRelativeAppIDPathAttr(), req.getServicePortAttr(),
130 TypeAttr::get(bundleType), b.getDictionaryAttr(channelAssignments),
131 DictionaryAttr());
132 }
133
134 // Erase the generation request.
135 implReq.erase();
136 return success();
137}
138
139// Generator for "sv_mem" implementation type. Emits SV ops for an unpacked
140// array, hopefully inferred as a memory to the SV compiler.
141static LogicalResult
142instantiateSystemVerilogMemory(ServiceImplementReqOp implReq,
143 ServiceDeclOpInterface decl,
144 ServiceImplRecordOp) {
145 if (!decl)
146 return implReq.emitOpError(
147 "Must specify a service declaration to use 'sv_mem'.");
148
149 ImplicitLocOpBuilder b(implReq.getLoc(), implReq);
150 BackedgeBuilder bb(b, implReq.getLoc());
151
152 RandomAccessMemoryDeclOp ramDecl =
153 dyn_cast<RandomAccessMemoryDeclOp>(decl.getOperation());
154 if (!ramDecl)
155 return implReq.emitOpError(
156 "'sv_mem' implementation type can only be used to "
157 "implement RandomAccessMemory declarations");
158
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");
165 auto none = b.create<hw::ConstantOp>(
166 APInt(/*numBits*/ 0, /*val*/ 0, /*isSigned*/ false));
167 auto i1 = b.getI1Type();
168 auto c0 = b.create<hw::ConstantOp>(i1, 0);
169
170 // List of reqs which have a result.
171 SmallVector<ServiceImplementConnReqOp, 8> toClientReqs(
172 llvm::make_filter_range(
173 implReq.getOps<ServiceImplementConnReqOp>(),
174 [](auto req) { return req.getToClient() != nullptr; }));
175
176 // Assemble a mapping of toClient results to actual consumers.
177 DenseMap<Value, Value> outputMap;
178 for (auto [bout, reqout] :
179 llvm::zip_longest(toClientReqs, implReq.getResults())) {
180 assert(bout.has_value());
181 assert(reqout.has_value());
182 Value toClient = bout->getToClient();
183 outputMap[toClient] = *reqout;
184 }
185
186 // Create the SV memory.
187 hw::UnpackedArrayType memType =
188 hw::UnpackedArrayType::get(ramDecl.getInnerType(), ramDecl.getDepth());
189 auto mem =
190 b.create<sv::RegOp>(memType, implReq.getServiceSymbolAttr().getAttr())
191 .getResult();
192
193 // Do everything which doesn't actually write to the memory, store the signals
194 // needed for the actual memory writes for later.
195 SmallVector<std::tuple<Value, Value, Value>> writeGoAddressData;
196 for (auto req : implReq.getOps<ServiceImplementConnReqOp>()) {
197 auto port = req.getServicePort().getName();
198 Value toClientResp;
199
200 if (port == write) {
201 // If this pair is doing a write...
202
203 // Construct the response channel.
204 auto doneValid = bb.get(i1);
205 auto ackChannel = b.create<WrapValidReadyOp>(none, doneValid);
206
207 auto pack =
208 b.create<PackBundleOp>(implReq.getLoc(), req.getToClient().getType(),
209 ackChannel.getChanOutput());
210 Value toServer =
211 pack.getFromChannels()[RandomAccessMemoryDeclOp::ReqDirChannelIdx];
212 toClientResp = pack.getBundle();
213
214 // Unwrap the write request and 'explode' the struct.
215 auto unwrap =
216 b.create<UnwrapValidReadyOp>(toServer, ackChannel.getReady());
217
218 Value address = b.create<hw::StructExtractOp>(unwrap.getRawOutput(),
219 b.getStringAttr("address"));
220 Value data = b.create<hw::StructExtractOp>(unwrap.getRawOutput(),
221 b.getStringAttr("data"));
222
223 // Determine if the write should occur this cycle.
224 auto go = b.create<comb::AndOp>(unwrap.getValid(), unwrap.getReady());
225 go->setAttr("sv.namehint", b.getStringAttr("write_go"));
226 // Register the 'go' signal and use it as the done message.
227 doneValid.setValue(
228 b.create<seq::CompRegOp>(go, clk, rst, c0, "write_done"));
229 // Store the necessary data for the 'always' memory writing block.
230 writeGoAddressData.push_back(std::make_tuple(go, address, data));
231
232 } else if (port == read) {
233 // If it's a read...
234
235 // Construct the response channel.
236 auto dataValid = bb.get(i1);
237 auto data = bb.get(ramDecl.getInnerType());
238 auto dataChannel = b.create<WrapValidReadyOp>(data, dataValid);
239
240 auto pack =
241 b.create<PackBundleOp>(implReq.getLoc(), req.getToClient().getType(),
242 dataChannel.getChanOutput());
243 Value toServer =
244 pack.getFromChannels()[RandomAccessMemoryDeclOp::RespDirChannelIdx];
245 toClientResp = pack.getBundle();
246
247 // Unwrap the requested address and read from that memory location.
248 auto addressUnwrap =
249 b.create<UnwrapValidReadyOp>(toServer, dataChannel.getReady());
250 Value memLoc =
251 b.create<sv::ArrayIndexInOutOp>(mem, addressUnwrap.getRawOutput());
252 auto readData = b.create<sv::ReadInOutOp>(memLoc);
253
254 // Set the data on the response.
255 data.setValue(readData);
256 dataValid.setValue(addressUnwrap.getValid());
257 } else {
258 assert(false && "Port should be either 'read' or 'write'");
259 }
260
261 outputMap[req.getToClient()].replaceAllUsesWith(toClientResp);
262 }
263
264 // Now construct the memory writes.
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; // So the lambda can capture.
271 // If we're told to go, do the write.
272 b.create<sv::IfOp>(go, [&] {
273 Value memLoc = b.create<sv::ArrayIndexInOutOp>(mem, a);
274 b.create<sv::PAssignOp>(memLoc, d);
275 });
276 }
277 });
278
279 implReq.erase();
280 return success();
281}
282
283//===----------------------------------------------------------------------===//
284// Service generator dispatcher.
285//===----------------------------------------------------------------------===//
286
287LogicalResult
288ServiceGeneratorDispatcher::generate(ServiceImplementReqOp req,
289 ServiceDeclOpInterface decl) {
290 // Lookup based on 'impl_type' attribute and pass through the generate request
291 // if found.
292 auto genF = genLookupTable.find(req.getImplTypeAttr().getValue());
293 if (genF == genLookupTable.end()) {
294 if (failIfNotFound)
295 return req.emitOpError("Could not find service generator for attribute '")
296 << req.getImplTypeAttr() << "'";
297 return success();
298 }
299
300 // Since we always need a record of generation, create it here then pass it to
301 // the generator for possible modification.
302 OpBuilder b(req);
303 auto implRecord = b.create<ServiceImplRecordOp>(
304 req.getLoc(), req.getAppID(), /*isEngine=*/false,
305 req.getServiceSymbolAttr(), req.getStdServiceAttr(),
306 req.getImplTypeAttr(), b.getDictionaryAttr({}));
307 implRecord.getReqDetails().emplaceBlock();
308
309 return genF->second(req, decl, implRecord);
310}
311
313 DenseMap<StringRef, ServiceGeneratorDispatcher::ServiceGeneratorFunc>{
316 false);
317
321
324 genLookupTable[implType] = std::move(gen);
325}
326
327//===----------------------------------------------------------------------===//
328// Wire up services pass.
329//===----------------------------------------------------------------------===//
330
331namespace {
332/// Find all the modules and use the partial order of the instantiation DAG
333/// to sort them. If we use this order when "bubbling" up operations, we
334/// guarantee one-pass completeness. As a side-effect, populate the module to
335/// instantiation sites mapping.
336///
337/// Assumption (unchecked): there is not a cycle in the instantiation graph.
338struct ModuleSorter {
339protected:
340 SymbolCache topLevelSyms;
341 DenseMap<Operation *, SmallVector<igraph::InstanceOpInterface, 1>>
342 moduleInstantiations;
343
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);
349};
350} // namespace
351
352void ModuleSorter::getAndSortModules(ModuleOp topMod,
353 SmallVectorImpl<hw::HWModuleLike> &mods) {
354 // Add here _before_ we go deeper to prevent infinite recursion.
355 DenseSet<Operation *> modsSeen;
356 mods.clear();
357 moduleInstantiations.clear();
358 topMod.walk([&](hw::HWModuleLike mod) {
359 getAndSortModulesVisitor(mod, mods, modsSeen);
360 });
361}
362
363// Run a post-order DFS.
364void ModuleSorter::getAndSortModulesVisitor(
365 hw::HWModuleLike mod, SmallVectorImpl<hw::HWModuleLike> &mods,
366 DenseSet<Operation *> &modsSeen) {
367 if (modsSeen.contains(mod))
368 return;
369 modsSeen.insert(mod);
370
371 mod.walk([&](igraph::InstanceOpInterface inst) {
372 auto targetNameAttrs = inst.getReferencedModuleNamesAttr();
373 for (auto targetNameAttr : targetNameAttrs) {
374 Operation *modOp =
375 topLevelSyms.getDefinition(cast<StringAttr>(targetNameAttr));
376 assert(modOp);
377 moduleInstantiations[modOp].push_back(inst);
378 if (auto modLike = dyn_cast<hw::HWModuleLike>(modOp))
379 getAndSortModulesVisitor(modLike, mods, modsSeen);
380 }
381 });
382
383 mods.push_back(mod);
384}
385namespace {
386/// Implements a pass to connect up ESI services clients to the nearest server
387/// instantiation. Wires up the ports and generates a generation request to
388/// call a user-specified generator.
389struct ESIConnectServicesPass
390 : public circt::esi::impl::ESIConnectServicesBase<ESIConnectServicesPass>,
391 ModuleSorter {
392
393 ESIConnectServicesPass(const ServiceGeneratorDispatcher &gen)
394 : genDispatcher(gen) {}
395 ESIConnectServicesPass()
396 : genDispatcher(ServiceGeneratorDispatcher::globalDispatcher()) {}
397
398 void runOnOperation() override;
399
400 /// Convert connection requests to service implement connection requests,
401 /// which have a relative appid path instead of just an appid. Leave being a
402 /// record for the manifest of the original request.
403 void convertReq(RequestConnectionOp);
404
405 /// "Bubble up" the specified requests to all of the instantiations of the
406 /// module specified. Create and connect up ports to tunnel the ESI channels
407 /// through.
408 LogicalResult surfaceReqs(hw::HWMutableModuleLike,
409 ArrayRef<ServiceImplementConnReqOp>);
410
411 /// For any service which is "local" (provides the requested service) in a
412 /// module, replace it with a ServiceImplementOp. Said op is to be replaced
413 /// with an instantiation by a generator.
414 LogicalResult replaceInst(ServiceInstanceOp,
415 ArrayRef<ServiceImplementConnReqOp> portReqs);
416
417 /// Figure out which requests are "local" vs need to be surfaced. Call
418 /// 'surfaceReqs' and/or 'replaceInst' as appropriate.
419 LogicalResult process(hw::HWModuleLike);
420
421 /// If the servicePort is referring to a std service, return the name of it.
422 StringAttr getStdService(FlatSymbolRefAttr serviceSym);
423
424private:
425 ServiceGeneratorDispatcher genDispatcher;
426};
427} // anonymous namespace
428
429void ESIConnectServicesPass::runOnOperation() {
430 ModuleOp outerMod = getOperation();
431 topLevelSyms.addDefinitions(outerMod);
432
433 outerMod.walk([&](RequestConnectionOp req) { convertReq(req); });
434
435 // Get a partially-ordered list of modules based on the instantiation DAG.
436 // It's _very_ important that we process modules before their instantiations
437 // so that the modules where they're instantiated correctly process the
438 // surfaced connections.
439 SmallVector<hw::HWModuleLike, 64> sortedMods;
440 getAndSortModules(outerMod, sortedMods);
441
442 // Process each module.
443 for (auto mod : sortedMods) {
444 hw::HWModuleLike mutableMod = dyn_cast<hw::HWModuleLike>(*mod);
445 if (mutableMod && failed(process(mutableMod))) {
446 signalPassFailure();
447 return;
448 }
449 }
450}
451
452// Get the std service name, if any.
453StringAttr ESIConnectServicesPass::getStdService(FlatSymbolRefAttr svcSym) {
454 if (!svcSym)
455 return {};
456 Operation *svcDecl = topLevelSyms.getDefinition(svcSym);
457 if (!isa<CustomServiceDeclOp>(svcDecl))
458 return svcDecl->getName().getIdentifier();
459 return {};
460}
461
462void ESIConnectServicesPass::convertReq(RequestConnectionOp req) {
463 OpBuilder b(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());
469
470 // Emit a record of the original request.
471 b.create<ServiceRequestRecordOp>(
472 req.getLoc(), req.getAppID(), req.getServicePortAttr(),
473 getStdService(req.getServicePortAttr().getModuleRef()),
474 req.getToClient().getType());
475 req.erase();
476}
477
478LogicalResult ESIConnectServicesPass::process(hw::HWModuleLike mod) {
479 // If 'mod' doesn't have a body, assume it's an external module.
480 if (mod->getNumRegions() == 0 || mod->getRegion(0).empty())
481 return success();
482
483 Block &modBlock = mod->getRegion(0).front();
484
485 // The non-local reqs which need to be surfaced from this module.
486 SetVector<ServiceImplementConnReqOp> nonLocalReqs;
487 // Index the local services and create blocks in which to put the requests.
488 llvm::MapVector<SymbolRefAttr, llvm::SetVector<ServiceImplementConnReqOp>>
489 localImplReqs;
490 for (auto instOp : modBlock.getOps<ServiceInstanceOp>())
491 localImplReqs[instOp.getServiceSymbolAttr()] = {};
492 // AFTER we assemble the local services table (and it will not change the
493 // location of the values), get the pointer to the default service instance,
494 // if any.
495 llvm::SetVector<ServiceImplementConnReqOp> *anyServiceInst = nullptr;
496 if (auto defaultService = localImplReqs.find(SymbolRefAttr());
497 defaultService != localImplReqs.end())
498 anyServiceInst = &defaultService->second;
499
500 auto sortConnReqs = [&]() {
501 // Sort the various requests by destination.
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);
510 else
511 nonLocalReqs.insert(req);
512 }
513 };
514 // Bootstrap the sorting.
515 sortConnReqs();
516
517 // Replace each service instance with a generation request. If a service
518 // generator is registered, generate the server.
519 for (auto instOp :
520 llvm::make_early_inc_range(modBlock.getOps<ServiceInstanceOp>())) {
521 auto portReqs = localImplReqs[instOp.getServiceSymbolAttr()];
522 if (failed(replaceInst(instOp, portReqs.getArrayRef())))
523 return failure();
524
525 // Find any new requests which were created by a generator.
526 for (RequestConnectionOp req : llvm::make_early_inc_range(
527 mod.getBodyBlock()->getOps<RequestConnectionOp>()))
528 convertReq(req);
529 sortConnReqs();
530 }
531
532 // Surface all of the requests which cannot be fulfilled locally.
533 if (nonLocalReqs.empty())
534 return success();
535
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");
540}
541
542LogicalResult ESIConnectServicesPass::replaceInst(
543 ServiceInstanceOp instOp, ArrayRef<ServiceImplementConnReqOp> portReqs) {
544 auto declSym = instOp.getServiceSymbolAttr();
545 ServiceDeclOpInterface decl;
546 if (declSym) {
547 decl = dyn_cast_or_null<ServiceDeclOpInterface>(
548 topLevelSyms.getDefinition(declSym));
549 if (!decl)
550 return instOp.emitOpError("Could not find service declaration ")
551 << declSym;
552 }
553
554 // Compute the result types for the new op -- the instance op's output types
555 // + the to_client types.
556 SmallVector<Type, 8> resultTypes(instOp.getResultTypes().begin(),
557 instOp.getResultTypes().end());
558 for (auto req : portReqs)
559 resultTypes.push_back(req.getBundleType());
560
561 // Create the generation request op.
562 OpBuilder b(instOp);
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();
569
570 // Update the users.
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));
578 }
579
580 for (auto req : portReqs)
581 req->moveBefore(&reqBlock, reqBlock.end());
582
583 // Erase the instance first in case it consumes any channels or bundles. If it
584 // does, the service generator will fail to verify the IR as there will be
585 // multiple uses.
586 instOp.erase();
587
588 // Try to generate the service provider.
589 if (failed(genDispatcher.generate(implOp, decl)))
590 return implOp.emitOpError("failed to generate server");
591
592 return success();
593}
594
595LogicalResult
596ESIConnectServicesPass::surfaceReqs(hw::HWMutableModuleLike mod,
597 ArrayRef<ServiceImplementConnReqOp> reqs) {
598 auto *ctxt = mod.getContext();
599 Block *body = &mod->getRegion(0).front();
600
601 // Track initial operand/result counts and the new IO.
602 unsigned origNumInputs = mod.getNumInputPorts();
603 SmallVector<std::pair<unsigned, hw::PortInfo>> newInputs;
604
605 // Assemble a port name from an array.
606 auto getPortName = [&](ArrayAttr namePath) {
607 std::string portName;
608 llvm::raw_string_ostream nameOS(portName);
609 llvm::interleave(
610 namePath.getAsRange<AppIDAttr>(), nameOS,
611 [&](AppIDAttr appid) {
612 nameOS << appid.getName().getValue();
613 if (appid.getIndex())
614 nameOS << "_" << appid.getIndex();
615 },
616 ".");
617 return StringAttr::get(ctxt, nameOS.str());
618 };
619
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");
624
625 // Insert new module input ESI ports.
626 for (auto req : reqs) {
627 newInputs.push_back(std::make_pair(
628 origNumInputs,
629 hw::PortInfo{{getPortName(req.getRelativeAppIDPathAttr()),
630 req.getBundleType(), hw::ModulePort::Direction::Input},
631 origNumInputs,
632 {},
633 req->getLoc()}));
634
635 // Replace uses with new block args which will correspond to said ports.
636 Value replValue = body->addArgument(req.getBundleType(), req->getLoc());
637 req.getToClient().replaceAllUsesWith(replValue);
638 }
639 mod.insertPorts(newInputs, {});
640
641 // Prepend a name to the instance tracking array.
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);
647 };
648
649 // Update the module instantiations.
650 SmallVector<igraph::InstanceOpInterface, 1> newModuleInstantiations;
651 for (auto inst : moduleInstantiations[mod]) {
652 OpBuilder b(inst);
653
654 // Add new inputs for the new bundles being requested.
655 SmallVector<Value, 16> newOperands;
656 for (auto req : reqs) {
657 // If the instance has an AppID, prepend it.
658 ArrayAttr appIDPath = req.getRelativeAppIDPathAttr();
659 if (auto instAppID = dyn_cast_or_null<AppIDAttr>(
660 inst->getDiscardableAttr(AppIDAttr::AppIDAttrName)))
661 appIDPath = prependNamePart(appIDPath, instAppID);
662
663 // Clone the request.
664 auto clone = b.create<ServiceImplementConnReqOp>(
665 req.getLoc(), req.getToClient().getType(), req.getServicePortAttr(),
666 appIDPath);
667 clone->setDialectAttrs(req->getDialectAttrs());
668 newOperands.push_back(clone.getToClient());
669 }
670 inst->insertOperands(inst->getNumOperands(), newOperands);
671 // Set the names, if we know how.
672 if (auto hwInst = dyn_cast<hw::InstanceOp>(*inst))
673 hwInst.setArgNamesAttr(b.getArrayAttr(mod.getInputNames()));
674 }
675
676 // Erase the original requests since they have been cloned into the proper
677 // destination modules.
678 for (auto req : reqs)
679 req.erase();
680 return success();
681}
682
683std::unique_ptr<OperationPass<ModuleOp>>
685 return std::make_unique<ESIConnectServicesPass>();
686}
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)
Definition OM.cpp:113
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...
Definition SymCache.h:85
Class which "dispatches" a service implementation request to its specified generator.
Definition ESIServices.h:24
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
Definition ESIServices.h:52
std::function< LogicalResult(ServiceImplementReqOp, ServiceDeclOpInterface, ServiceImplRecordOp)> ServiceGeneratorFunc
Definition ESIServices.h:28
create(data_type, value)
Definition hw.py:433
create(struct_value, str field_name)
Definition hw.py:556
Definition sv.py:68
std::unique_ptr< OperationPass< ModuleOp > > createESIConnectServicesPass()
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Definition esi.py:1
This holds the name, type, direction of a module's ports.