CIRCT 22.0.0git
Loading...
Searching...
No Matches
ESILowerToHW.cpp
Go to the documentation of this file.
1//===- ESILowerToHW.cpp - Lower ESI to HW -----------------------*- C++ -*-===//
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// Lower to HW/SV conversions and pass.
10//
11//===----------------------------------------------------------------------===//
12
13#include "../PassDetails.h"
14
21#include "circt/Support/LLVM.h"
23
24#include "mlir/Transforms/DialectConversion.h"
25
26#include "llvm/ADT/StringExtras.h"
27#include "llvm/ADT/TypeSwitch.h"
28#include "llvm/Support/JSON.h"
29
30namespace circt {
31namespace esi {
32#define GEN_PASS_DEF_LOWERESITOHW
33#include "circt/Dialect/ESI/ESIPasses.h.inc"
34} // namespace esi
35} // namespace circt
36
37using namespace circt;
38using namespace circt::esi;
39using namespace circt::esi::detail;
40using namespace circt::hw;
41using namespace circt::sv;
42
43namespace {
44/// Lower PipelineStageOp ops to an HW implementation. Unwrap and re-wrap
45/// appropriately. Another conversion will take care merging the resulting
46/// adjacent wrap/unwrap ops.
47struct PipelineStageLowering : public OpConversionPattern<PipelineStageOp> {
48public:
49 PipelineStageLowering(ESIHWBuilder &builder, MLIRContext *ctxt)
50 : OpConversionPattern(ctxt), builder(builder) {}
51 using OpConversionPattern::OpConversionPattern;
52
53 LogicalResult
54 matchAndRewrite(PipelineStageOp stage, OpAdaptor adaptor,
55 ConversionPatternRewriter &rewriter) const final;
56
57private:
58 ESIHWBuilder &builder;
59};
60} // anonymous namespace
61
62LogicalResult PipelineStageLowering::matchAndRewrite(
63 PipelineStageOp stage, OpAdaptor adaptor,
64 ConversionPatternRewriter &rewriter) const {
65 auto loc = stage.getLoc();
66 auto chPort = dyn_cast<ChannelType>(stage.getInput().getType());
67 if (!chPort)
68 return rewriter.notifyMatchFailure(stage, "stage had wrong type");
69 Operation *symTable = stage->getParentWithTrait<OpTrait::SymbolTable>();
70 auto stageModule = builder.declareStage(symTable, stage);
71
72 size_t width = circt::hw::getBitWidth(chPort.getInner());
73
74 ArrayAttr stageParams =
75 builder.getStageParameterList(rewriter.getUI32IntegerAttr(width));
76
77 // Unwrap the channel. The ready signal is a Value we haven't created yet,
78 // so create a temp value and replace it later. Give this constant an
79 // odd-looking type to make debugging easier.
80 circt::BackedgeBuilder back(rewriter, loc);
81 circt::Backedge wrapReady = back.get(rewriter.getI1Type());
82 auto unwrap =
83 UnwrapValidReadyOp::create(rewriter, loc, stage.getInput(), wrapReady);
84
85 StringRef pipeStageName = "pipelineStage";
86 if (auto name = stage->getAttrOfType<StringAttr>("name"))
87 pipeStageName = name.getValue();
88
89 // Instantiate the "ESI_PipelineStage" external module.
90 circt::Backedge stageReady = back.get(rewriter.getI1Type());
91 llvm::SmallVector<Value> operands = {stage.getClk(), stage.getRst()};
92 operands.push_back(unwrap.getRawOutput());
93 operands.push_back(unwrap.getValid());
94 operands.push_back(stageReady);
95 auto stageInst = hw::InstanceOp::create(rewriter, loc, stageModule,
96 pipeStageName, operands, stageParams);
97 auto stageInstResults = stageInst.getResults();
98
99 // Set a_ready (from the unwrap) back edge correctly to its output from
100 // stage.
101 wrapReady.setValue(stageInstResults[0]);
102 Value x, xValid;
103 x = stageInstResults[1];
104 xValid = stageInstResults[2];
105
106 // Wrap up the output of the HW stage module.
107 auto wrap = WrapValidReadyOp::create(rewriter, loc, chPort,
108 rewriter.getI1Type(), x, xValid);
109 // Set the stages x_ready backedge correctly.
110 stageReady.setValue(wrap.getReady());
111
112 rewriter.replaceOp(stage, wrap.getChanOutput());
113 return success();
114}
115
116namespace {
117struct NullSourceOpLowering : public OpConversionPattern<NullSourceOp> {
118public:
119 NullSourceOpLowering(MLIRContext *ctxt) : OpConversionPattern(ctxt) {}
120 using OpConversionPattern::OpConversionPattern;
121
122 LogicalResult
123 matchAndRewrite(NullSourceOp nullop, OpAdaptor adaptor,
124 ConversionPatternRewriter &rewriter) const final;
125};
126} // anonymous namespace
127
128LogicalResult NullSourceOpLowering::matchAndRewrite(
129 NullSourceOp nullop, OpAdaptor adaptor,
130 ConversionPatternRewriter &rewriter) const {
131 auto innerType = cast<ChannelType>(nullop.getOut().getType()).getInner();
132 Location loc = nullop.getLoc();
133 int64_t width = hw::getBitWidth(innerType);
134 if (width == -1)
135 return rewriter.notifyMatchFailure(
136 nullop, "NullOp lowering only supports hw types");
137 auto valid = hw::ConstantOp::create(rewriter, nullop.getLoc(),
138 rewriter.getI1Type(), 0);
139 auto zero =
140 hw::ConstantOp::create(rewriter, loc, rewriter.getIntegerType(width), 0);
141 auto typedZero = hw::BitcastOp::create(rewriter, loc, innerType, zero);
142 auto wrap = WrapValidReadyOp::create(rewriter, loc, typedZero, valid);
143 wrap->setAttr("name", rewriter.getStringAttr("nullsource"));
144 rewriter.replaceOp(nullop, {wrap.getChanOutput()});
145 return success();
146}
147
148namespace {
149/// Eliminate back-to-back wrap-unwraps to reduce the number of ESI channels.
150struct RemoveWrapUnwrap : public ConversionPattern {
151public:
152 RemoveWrapUnwrap(MLIRContext *context)
153 : ConversionPattern(MatchAnyOpTypeTag(), /*benefit=*/1, context) {}
154
155 LogicalResult
156 matchAndRewrite(Operation *op, ArrayRef<Value> operands,
157 ConversionPatternRewriter &rewriter) const override {
158 Value valid, ready, data;
159 WrapValidReadyOp wrap = dyn_cast<WrapValidReadyOp>(op);
160 UnwrapValidReadyOp unwrap = dyn_cast<UnwrapValidReadyOp>(op);
161 if (wrap) {
162 if (ChannelType::hasNoConsumers(wrap.getChanOutput())) {
163 auto c1 = hw::ConstantOp::create(rewriter, wrap.getLoc(),
164 rewriter.getI1Type(), 1);
165 rewriter.replaceOp(wrap, {nullptr, c1});
166 return success();
167 }
168
169 if (!ChannelType::hasOneConsumer(wrap.getChanOutput()))
170 return rewriter.notifyMatchFailure(
171 wrap, "This conversion only supports wrap-unwrap back-to-back. "
172 "Wrap didn't have exactly one use.");
173 if (!(unwrap = dyn_cast<UnwrapValidReadyOp>(
174 ChannelType::getSingleConsumer(wrap.getChanOutput())
175 ->getOwner())))
176 return rewriter.notifyMatchFailure(
177 wrap, "This conversion only supports wrap-unwrap back-to-back. "
178 "Could not find 'unwrap'.");
179
180 data = operands[0];
181 valid = operands[1];
182 ready = unwrap.getReady();
183 } else if (unwrap) {
184 Operation *defOp = operands[0].getDefiningOp();
185 if (!defOp)
186 return rewriter.notifyMatchFailure(
187 unwrap, "unwrap input is not defined by an op");
188 wrap = dyn_cast<WrapValidReadyOp>(defOp);
189 if (!wrap)
190 return rewriter.notifyMatchFailure(
191 operands[0].getDefiningOp(),
192 "This conversion only supports wrap-unwrap back-to-back. "
193 "Could not find 'wrap'.");
194 valid = wrap.getValid();
195 data = wrap.getRawInput();
196 ready = operands[1];
197 } else {
198 return failure();
199 }
200
201 if (!ChannelType::hasOneConsumer(wrap.getChanOutput()))
202 return rewriter.notifyMatchFailure(wrap, [](Diagnostic &d) {
203 d << "This conversion only supports wrap-unwrap back-to-back. "
204 "Wrap didn't have exactly one use.";
205 });
206 rewriter.replaceOp(wrap, {nullptr, ready});
207 rewriter.replaceOp(unwrap, {data, valid});
208 return success();
209 }
210};
211} // anonymous namespace
212
213namespace {
214/// Eliminate snoop operations in wrap-unwrap pairs.
215struct RemoveSnoopOp : public OpConversionPattern<SnoopValidReadyOp> {
216public:
217 using OpConversionPattern::OpConversionPattern;
218
219 LogicalResult
220 matchAndRewrite(SnoopValidReadyOp op, SnoopValidReadyOpAdaptor operands,
221 ConversionPatternRewriter &rewriter) const override {
222 Operation *defOp = op.getInput().getDefiningOp();
223 if (!defOp)
224 return rewriter.notifyMatchFailure(op,
225 "snoop input is not defined by an op");
226 auto wrap = dyn_cast<WrapValidReadyOp>(defOp);
227 if (!wrap)
228 return rewriter.notifyMatchFailure(
229 defOp, "This conversion only supports wrap-unwrap back-to-back. "
230 "Could not find 'wrap'.");
231 auto *unwrapOpOperand =
232 ChannelType::getSingleConsumer(wrap.getChanOutput());
233 if (!unwrapOpOperand)
234 return rewriter.notifyMatchFailure(
235 defOp, "This conversion only supports wrap-unwrap back-to-back. "
236 "Could sole consumer.");
237 auto unwrap = dyn_cast<UnwrapValidReadyOp>(unwrapOpOperand->getOwner());
238 if (!unwrap)
239 return rewriter.notifyMatchFailure(
240 defOp, "This conversion only supports wrap-unwrap back-to-back. "
241 "Could not find 'unwrap'.");
242 rewriter.replaceOp(
243 op, {wrap.getValid(), unwrap.getReady(), wrap.getRawInput()});
244 return success();
245 }
246};
247} // anonymous namespace
248
249namespace {
250/// Eliminate snoop transaction operations in wrap-unwrap pairs.
251struct RemoveSnoopTransactionOp
252 : public OpConversionPattern<SnoopTransactionOp> {
253public:
254 using OpConversionPattern::OpConversionPattern;
255
256 LogicalResult
257 matchAndRewrite(SnoopTransactionOp op, SnoopTransactionOpAdaptor operands,
258 ConversionPatternRewriter &rewriter) const override {
259 Operation *defOp = op.getInput().getDefiningOp();
260 if (!defOp)
261 return rewriter.notifyMatchFailure(op,
262 "snoop input is not defined by an op");
263
264 // Handle ValidReady signaling
265 if (auto wrapVR = dyn_cast<WrapValidReadyOp>(defOp)) {
266 auto *unwrapOpOperand =
267 ChannelType::getSingleConsumer(wrapVR.getChanOutput());
268 if (!unwrapOpOperand)
269 return rewriter.notifyMatchFailure(
270 defOp, "This conversion only supports wrap-unwrap back-to-back. "
271 "Could not find sole consumer.");
272 auto unwrapVR = dyn_cast<UnwrapValidReadyOp>(unwrapOpOperand->getOwner());
273 if (!unwrapVR)
274 return rewriter.notifyMatchFailure(
275 defOp, "This conversion only supports wrap-unwrap back-to-back. "
276 "Could not find 'unwrap'.");
277
278 // Create transaction signal as valid AND ready
279 auto validAndReady = comb::AndOp::create(
280 rewriter, op.getLoc(), wrapVR.getValid(), unwrapVR.getReady());
281
282 rewriter.replaceOp(op, {validAndReady, wrapVR.getRawInput()});
283 return success();
284 }
285
286 // Handle FIFO signaling
287 if (auto wrapFIFO = dyn_cast<WrapFIFOOp>(defOp)) {
288 auto *unwrapOpOperand =
289 ChannelType::getSingleConsumer(wrapFIFO.getChanOutput());
290 if (!unwrapOpOperand)
291 return rewriter.notifyMatchFailure(
292 defOp, "This conversion only supports wrap-unwrap back-to-back. "
293 "Could not find sole consumer.");
294 auto unwrapFIFO = dyn_cast<UnwrapFIFOOp>(unwrapOpOperand->getOwner());
295 if (!unwrapFIFO)
296 return rewriter.notifyMatchFailure(
297 defOp, "This conversion only supports wrap-unwrap back-to-back. "
298 "Could not find 'unwrap'.");
299
300 // Create transaction signal as !empty AND rden
301 auto notEmpty = comb::XorOp::create(
302 rewriter, op.getLoc(), wrapFIFO.getEmpty(),
303 hw::ConstantOp::create(rewriter, op.getLoc(),
304 rewriter.getBoolAttr(true)));
305 auto transaction = comb::AndOp::create(rewriter, op.getLoc(), notEmpty,
306 unwrapFIFO.getRden());
307
308 rewriter.replaceOp(op, {transaction, wrapFIFO.getData()});
309 return success();
310 }
311
312 return rewriter.notifyMatchFailure(
313 defOp, "This conversion only supports wrap-unwrap back-to-back for "
314 "ValidReady and FIFO signaling.");
315 }
316};
317} // anonymous namespace
318
319namespace {
320/// Use the op canonicalizer to lower away the op. Assumes the canonicalizer
321/// deletes the op.
322template <typename Op>
323struct CanonicalizerOpLowering : public OpConversionPattern<Op> {
324public:
325 CanonicalizerOpLowering(MLIRContext *ctxt) : OpConversionPattern<Op>(ctxt) {}
326
327 LogicalResult
328 matchAndRewrite(Op op, typename Op::Adaptor adaptor,
329 ConversionPatternRewriter &rewriter) const final {
330 if (failed(Op::canonicalize(op, rewriter)))
331 return rewriter.notifyMatchFailure(op->getLoc(), "canonicalizer failed");
332 return success();
333 }
334};
335} // anonymous namespace
336
337namespace {
338struct ESItoHWPass : public circt::esi::impl::LowerESItoHWBase<ESItoHWPass> {
339 void runOnOperation() override;
340};
341} // anonymous namespace
342
343namespace {
344/// Lower a `wrap.iface` to `wrap.vr` by extracting the wires then feeding the
345/// new `wrap.vr`.
346struct WrapInterfaceLower : public OpConversionPattern<WrapSVInterfaceOp> {
347public:
348 using OpConversionPattern::OpConversionPattern;
349
350 LogicalResult
351 matchAndRewrite(WrapSVInterfaceOp wrap, OpAdaptor adaptor,
352 ConversionPatternRewriter &rewriter) const final;
353};
354} // anonymous namespace
355
356LogicalResult
357WrapInterfaceLower::matchAndRewrite(WrapSVInterfaceOp wrap, OpAdaptor adaptor,
358 ConversionPatternRewriter &rewriter) const {
359 auto operands = adaptor.getOperands();
360 if (operands.size() != 1)
361 return rewriter.notifyMatchFailure(wrap, [&operands](Diagnostic &d) {
362 d << "wrap.iface has 1 argument. Got " << operands.size() << "operands";
363 });
364 auto sinkModport = dyn_cast<GetModportOp>(operands[0].getDefiningOp());
365 if (!sinkModport)
366 return failure();
367 auto ifaceInstance =
368 dyn_cast<InterfaceInstanceOp>(sinkModport.getIface().getDefiningOp());
369 if (!ifaceInstance)
370 return failure();
371
372 auto loc = wrap.getLoc();
373 auto validSignal = ReadInterfaceSignalOp::create(rewriter, loc, ifaceInstance,
375 Value dataSignal;
376 dataSignal = ReadInterfaceSignalOp::create(rewriter, loc, ifaceInstance,
378 auto wrapVR =
379 WrapValidReadyOp::create(rewriter, loc, dataSignal, validSignal);
380 AssignInterfaceSignalOp::create(rewriter, loc, ifaceInstance,
381 ESIHWBuilder::readyStr, wrapVR.getReady());
382 rewriter.replaceOp(wrap, {wrapVR.getChanOutput()});
383 return success();
384}
385
386namespace {
387/// Lower an unwrap interface to just extract the wires and feed them into an
388/// `unwrap.vr`.
389struct UnwrapInterfaceLower : public OpConversionPattern<UnwrapSVInterfaceOp> {
390public:
391 UnwrapInterfaceLower(MLIRContext *ctxt) : OpConversionPattern(ctxt) {}
392 using OpConversionPattern::OpConversionPattern;
393
394 LogicalResult
395 matchAndRewrite(UnwrapSVInterfaceOp wrap, OpAdaptor adaptor,
396 ConversionPatternRewriter &rewriter) const final;
397};
398} // anonymous namespace
399
400LogicalResult UnwrapInterfaceLower::matchAndRewrite(
401 UnwrapSVInterfaceOp unwrap, OpAdaptor adaptor,
402 ConversionPatternRewriter &rewriter) const {
403 auto operands = adaptor.getOperands();
404 if (operands.size() != 2)
405 return rewriter.notifyMatchFailure(unwrap, [&operands](Diagnostic &d) {
406 d << "Unwrap.iface has 2 arguments. Got " << operands.size()
407 << "operands";
408 });
409
410 auto sourceModport = dyn_cast<GetModportOp>(operands[1].getDefiningOp());
411 if (!sourceModport)
412 return failure();
413 auto ifaceInstance =
414 dyn_cast<InterfaceInstanceOp>(sourceModport.getIface().getDefiningOp());
415 if (!ifaceInstance)
416 return failure();
417
418 auto loc = unwrap.getLoc();
419 auto readySignal = ReadInterfaceSignalOp::create(rewriter, loc, ifaceInstance,
421 auto unwrapVR =
422 UnwrapValidReadyOp::create(rewriter, loc, operands[0], readySignal);
423 AssignInterfaceSignalOp::create(rewriter, loc, ifaceInstance,
424 ESIHWBuilder::validStr, unwrapVR.getValid());
425
426 AssignInterfaceSignalOp::create(rewriter, loc, ifaceInstance,
428 unwrapVR.getRawOutput());
429 rewriter.eraseOp(unwrap);
430 return success();
431}
432
433namespace {
434/// Lower `CosimEndpointOp` ops to a SystemVerilog extern module and a Capnp
435/// gasket op.
436struct CosimToHostLowering : public OpConversionPattern<CosimToHostEndpointOp> {
437public:
438 CosimToHostLowering(ESIHWBuilder &b)
439 : OpConversionPattern(b.getContext(), 1), builder(b) {}
440
441 using OpConversionPattern::OpConversionPattern;
442
443 LogicalResult
444 matchAndRewrite(CosimToHostEndpointOp, OpAdaptor adaptor,
445 ConversionPatternRewriter &rewriter) const final;
446
447private:
448 ESIHWBuilder &builder;
449};
450} // anonymous namespace
451
452LogicalResult CosimToHostLowering::matchAndRewrite(
453 CosimToHostEndpointOp ep, OpAdaptor adaptor,
454 ConversionPatternRewriter &rewriter) const {
455 auto loc = ep.getLoc();
456 auto *ctxt = rewriter.getContext();
457 circt::BackedgeBuilder bb(rewriter, loc);
458
459 Value toHost = adaptor.getToHost();
460 Type type = toHost.getType();
461 uint64_t width = getWidth(type);
462
463 // Set all the parameters.
464 SmallVector<Attribute, 8> params;
465 params.push_back(ParamDeclAttr::get("ENDPOINT_ID", ep.getIdAttr()));
466 params.push_back(ParamDeclAttr::get("TO_HOST_TYPE_ID", getTypeID(type)));
467 params.push_back(ParamDeclAttr::get(
468 "TO_HOST_SIZE_BITS", rewriter.getI32IntegerAttr(width > 0 ? width : 1)));
469
470 // Set up the egest route to drive the EP's toHost ports.
471 auto sendReady = bb.get(rewriter.getI1Type());
472 UnwrapValidReadyOp unwrapSend =
473 UnwrapValidReadyOp::create(rewriter, loc, toHost, sendReady);
474 Value castedSendData;
475 if (width > 0)
476 castedSendData =
477 hw::BitcastOp::create(rewriter, loc, rewriter.getIntegerType(width),
478 unwrapSend.getRawOutput());
479 else
480 castedSendData = hw::ConstantOp::create(
481 rewriter, loc, rewriter.getIntegerType(1), rewriter.getBoolAttr(false));
482
483 // Build or get the cached Cosim Endpoint module parameterization.
484 Operation *symTable = ep->getParentWithTrait<OpTrait::SymbolTable>();
485 HWModuleExternOp endpoint =
486 builder.declareCosimEndpointToHostModule(symTable);
487
488 // Create replacement Cosim_Endpoint instance.
489 Value operands[] = {
490 adaptor.getClk(),
491 adaptor.getRst(),
492 unwrapSend.getValid(),
493 castedSendData,
494 };
495 auto cosimEpModule =
496 hw::InstanceOp::create(rewriter, loc, endpoint, ep.getIdAttr(), operands,
497 ArrayAttr::get(ctxt, params));
498 sendReady.setValue(cosimEpModule.getResult(0));
499
500 // Replace the CosimEndpointOp op.
501 rewriter.eraseOp(ep);
502
503 return success();
504}
505
506namespace {
507/// Lower `CosimEndpointOp` ops to a SystemVerilog extern module and a Capnp
508/// gasket op.
509struct CosimFromHostLowering
510 : public OpConversionPattern<CosimFromHostEndpointOp> {
511public:
512 CosimFromHostLowering(ESIHWBuilder &b)
513 : OpConversionPattern(b.getContext(), 1), builder(b) {}
514
515 using OpConversionPattern::OpConversionPattern;
516
517 LogicalResult
518 matchAndRewrite(CosimFromHostEndpointOp, OpAdaptor adaptor,
519 ConversionPatternRewriter &rewriter) const final;
520
521private:
522 ESIHWBuilder &builder;
523};
524} // anonymous namespace
525
526LogicalResult CosimFromHostLowering::matchAndRewrite(
527 CosimFromHostEndpointOp ep, OpAdaptor adaptor,
528 ConversionPatternRewriter &rewriter) const {
529 auto loc = ep.getLoc();
530 auto *ctxt = rewriter.getContext();
531 circt::BackedgeBuilder bb(rewriter, loc);
532
533 ChannelType type = ep.getFromHost().getType();
534 uint64_t width = getWidth(type);
535
536 // Set all the parameters.
537 SmallVector<Attribute, 8> params;
538 params.push_back(ParamDeclAttr::get("ENDPOINT_ID", ep.getIdAttr()));
539 params.push_back(ParamDeclAttr::get("FROM_HOST_TYPE_ID", getTypeID(type)));
540 params.push_back(
541 ParamDeclAttr::get("FROM_HOST_SIZE_BITS",
542 rewriter.getI32IntegerAttr(width > 0 ? width : 1)));
543
544 // Get information necessary for injest path.
545 auto recvReady = bb.get(rewriter.getI1Type());
546
547 // Build or get the cached Cosim Endpoint module parameterization.
548 Operation *symTable = ep->getParentWithTrait<OpTrait::SymbolTable>();
549 HWModuleExternOp endpoint =
550 builder.declareCosimEndpointFromHostModule(symTable);
551
552 // Create replacement Cosim_Endpoint instance.
553 Value operands[] = {adaptor.getClk(), adaptor.getRst(), recvReady};
554 auto cosimEpModule =
555 hw::InstanceOp::create(rewriter, loc, endpoint, ep.getIdAttr(), operands,
556 ArrayAttr::get(ctxt, params));
557
558 // Set up the injest path.
559 Value recvDataFromCosim = cosimEpModule.getResult(1);
560 Value recvValidFromCosim = cosimEpModule.getResult(0);
561 Value castedRecvData;
562 if (width > 0)
563 castedRecvData = hw::BitcastOp::create(rewriter, loc, type.getInner(),
564 recvDataFromCosim);
565 else
566 castedRecvData = hw::ConstantOp::create(
567 rewriter, loc, rewriter.getIntegerType(0),
568 rewriter.getIntegerAttr(rewriter.getIntegerType(0), 0));
569 WrapValidReadyOp wrapRecv = WrapValidReadyOp::create(
570 rewriter, loc, castedRecvData, recvValidFromCosim);
571 recvReady.setValue(wrapRecv.getReady());
572
573 // Replace the CosimEndpointOp op.
574 rewriter.replaceOp(ep, wrapRecv.getChanOutput());
575
576 return success();
577}
578
579namespace {
580/// Lower `CompressedManifestOps` ops to a module containing an on-chip ROM.
581/// Said module has registered input and outputs, so it has two cycles latency
582/// between changing the address and the data being reflected on the output.
583struct ManifestRomLowering : public OpConversionPattern<CompressedManifestOp> {
584public:
585 using OpConversionPattern::OpConversionPattern;
586 constexpr static StringRef manifestRomName = "__ESI_Manifest_ROM";
587
588 LogicalResult
589 matchAndRewrite(CompressedManifestOp, OpAdaptor adaptor,
590 ConversionPatternRewriter &rewriter) const override;
591
592protected:
593 LogicalResult createRomModule(CompressedManifestOp op,
594 ConversionPatternRewriter &rewriter) const;
595};
596} // anonymous namespace
597
598LogicalResult ManifestRomLowering::createRomModule(
599 CompressedManifestOp op, ConversionPatternRewriter &rewriter) const {
600 Location loc = op.getLoc();
601 auto mlirModBody = op->getParentOfType<mlir::ModuleOp>();
602 rewriter.setInsertionPointToStart(mlirModBody.getBody());
603
604 // Find possible existing module (which may have been created as a dummy
605 // module) and erase it.
606 if (Operation *existingExtern = mlirModBody.lookupSymbol(manifestRomName)) {
607 if (!isa<hw::HWModuleExternOp>(existingExtern))
608 return rewriter.notifyMatchFailure(
609 op,
610 "Found " + manifestRomName + " but it wasn't an HWModuleExternOp");
611 rewriter.eraseOp(existingExtern);
612 }
613
614 // Create the real module.
615 PortInfo ports[] = {
616 {{rewriter.getStringAttr("clk"), rewriter.getType<seq::ClockType>(),
617 ModulePort::Direction::Input}},
618 {{rewriter.getStringAttr("address"), rewriter.getIntegerType(29),
619 ModulePort::Direction::Input}},
620 {{rewriter.getStringAttr("data"), rewriter.getI64Type(),
621 ModulePort::Direction::Output}},
622 };
623 auto rom = HWModuleOp::create(rewriter, loc,
624 rewriter.getStringAttr(manifestRomName), ports);
625 Block *romBody = rom.getBodyBlock();
626 rewriter.setInsertionPointToStart(romBody);
627 Value clk = romBody->getArgument(0);
628 Value inputAddress = romBody->getArgument(1);
629
630 // Manifest the compressed manifest into 64-bit words.
631 ArrayRef<uint8_t> maniBytes = op.getCompressedManifest().getData();
632 SmallVector<uint64_t> words;
633 words.push_back(maniBytes.size());
634
635 for (size_t i = 0; i < maniBytes.size() - 7; i += 8) {
636 uint64_t word = 0;
637 for (size_t b = 0; b < 8; ++b)
638 word |= static_cast<uint64_t>(maniBytes[i + b]) << (8 * b);
639 words.push_back(word);
640 }
641 size_t overHang = maniBytes.size() % 8;
642 if (overHang != 0) {
643 uint64_t word = 0;
644 for (size_t i = 0; i < overHang; ++i)
645 word |= static_cast<uint64_t>(maniBytes[maniBytes.size() - overHang + i])
646 << (i * 8);
647 words.push_back(word);
648 }
649
650 // From the words, create an the register which will hold the manifest (and
651 // hopefully synthized to a ROM).
652 SmallVector<Attribute> wordAttrs;
653 for (uint64_t word : words)
654 wordAttrs.push_back(rewriter.getI64IntegerAttr(word));
655 auto manifestConstant = hw::AggregateConstantOp::create(
656 rewriter, loc,
657 hw::UnpackedArrayType::get(rewriter.getI64Type(), words.size()),
658 rewriter.getArrayAttr(wordAttrs));
659 auto manifestReg =
660 sv::RegOp::create(rewriter, loc, manifestConstant.getType());
661 sv::AssignOp::create(rewriter, loc, manifestReg, manifestConstant);
662
663 // Slim down the address, register it, do the lookup, and register the output.
664 size_t addrBits = llvm::Log2_64_Ceil(words.size());
665 auto slimmedIdx =
666 comb::ExtractOp::create(rewriter, loc, inputAddress, 0, addrBits);
667 Value inputAddresReg = seq::CompRegOp::create(rewriter, loc, slimmedIdx, clk);
668 auto readIdx =
669 sv::ArrayIndexInOutOp::create(rewriter, loc, manifestReg, inputAddresReg);
670 auto readData = sv::ReadInOutOp::create(rewriter, loc, readIdx);
671 Value readDataReg = seq::CompRegOp::create(rewriter, loc, readData, clk);
672 if (auto *term = romBody->getTerminator())
673 rewriter.eraseOp(term);
674 hw::OutputOp::create(rewriter, loc, ValueRange{readDataReg});
675 return success();
676}
677
678LogicalResult ManifestRomLowering::matchAndRewrite(
679 CompressedManifestOp op, OpAdaptor adaptor,
680 ConversionPatternRewriter &rewriter) const {
681 LogicalResult ret = createRomModule(op, rewriter);
682 rewriter.eraseOp(op);
683 return ret;
684}
685
686namespace {
687/// Lower `CompressedManifestOps` ops to a SystemVerilog module which sets the
688/// Cosim manifest using a DPI support module.
689struct CosimManifestLowering : public ManifestRomLowering {
690public:
691 using ManifestRomLowering::ManifestRomLowering;
692
693 LogicalResult
694 matchAndRewrite(CompressedManifestOp, OpAdaptor adaptor,
695 ConversionPatternRewriter &rewriter) const final;
696};
697} // anonymous namespace
698
699LogicalResult CosimManifestLowering::matchAndRewrite(
700 CompressedManifestOp op, OpAdaptor adaptor,
701 ConversionPatternRewriter &rewriter) const {
702 MLIRContext *ctxt = rewriter.getContext();
703 Location loc = op.getLoc();
704
705 // Cosim can optionally include a manifest simulation, so produce it in case
706 // the Cosim BSP wants it.
707 LogicalResult ret = createRomModule(op, rewriter);
708 if (failed(ret))
709 return ret;
710
711 // Declare external module.
712 Attribute params[] = {
713 ParamDeclAttr::get("COMPRESSED_MANIFEST_SIZE", rewriter.getI32Type())};
714 PortInfo ports[] = {
715 {{rewriter.getStringAttr("compressed_manifest"),
716 rewriter.getType<hw::ArrayType>(
717 rewriter.getI8Type(),
718 ParamDeclRefAttr::get(
719 rewriter.getStringAttr("COMPRESSED_MANIFEST_SIZE"),
720 rewriter.getI32Type())),
721 ModulePort::Direction::Input},
722 0},
723 };
724 rewriter.setInsertionPointToEnd(
725 op->getParentOfType<mlir::ModuleOp>().getBody());
726 auto cosimManifestExternModule = HWModuleExternOp::create(
727 rewriter, loc, rewriter.getStringAttr("Cosim_Manifest"), ports,
728 "Cosim_Manifest", ArrayAttr::get(ctxt, params));
729
730 hw::ModulePortInfo portInfo({});
731 auto manifestMod = hw::HWModuleOp::create(
732 rewriter, loc, rewriter.getStringAttr("__ESIManifest"), portInfo,
733 [&](OpBuilder &rewriter, const hw::HWModulePortAccessor &) {
734 // Assemble the manifest data into a constant.
735 SmallVector<Attribute> bytes;
736 for (uint8_t b : op.getCompressedManifest().getData())
737 bytes.push_back(rewriter.getI8IntegerAttr(b));
738 auto manifestConstant = hw::AggregateConstantOp::create(
739 rewriter, loc,
740 hw::ArrayType::get(rewriter.getI8Type(), bytes.size()),
741 rewriter.getArrayAttr(bytes));
742 auto manifestLogic =
743 sv::LogicOp::create(rewriter, loc, manifestConstant.getType());
744 sv::AssignOp::create(rewriter, loc, manifestLogic, manifestConstant);
745 auto manifest = sv::ReadInOutOp::create(rewriter, loc, manifestLogic);
746
747 // Then instantiate the external module.
748 hw::InstanceOp::create(rewriter, loc, cosimManifestExternModule,
749 "__manifest", ArrayRef<Value>({manifest}),
750 rewriter.getArrayAttr({ParamDeclAttr::get(
751 "COMPRESSED_MANIFEST_SIZE",
752 rewriter.getI32IntegerAttr(bytes.size()))}));
753 });
754
755 rewriter.setInsertionPoint(op);
756 hw::InstanceOp::create(rewriter, loc, manifestMod, "__manifest",
757 ArrayRef<Value>({}));
758
759 rewriter.eraseOp(op);
760 return success();
761}
762void ESItoHWPass::runOnOperation() {
763 auto top = getOperation();
764 auto *ctxt = &getContext();
765
766 // Lower all the bundles.
767 ConversionTarget noBundlesTarget(*ctxt);
768 noBundlesTarget.markUnknownOpDynamicallyLegal(
769 [](Operation *) { return true; });
770 noBundlesTarget.addIllegalOp<PackBundleOp>();
771 noBundlesTarget.addIllegalOp<UnpackBundleOp>();
772 RewritePatternSet bundlePatterns(&getContext());
773 bundlePatterns.add<CanonicalizerOpLowering<PackBundleOp>>(&getContext());
774 bundlePatterns.add<CanonicalizerOpLowering<UnpackBundleOp>>(&getContext());
775 if (failed(applyPartialConversion(getOperation(), noBundlesTarget,
776 std::move(bundlePatterns)))) {
777 signalPassFailure();
778 return;
779 }
780
781 // Set up a conversion and give it a set of laws.
782 ConversionTarget pass1Target(*ctxt);
783 pass1Target.addLegalDialect<comb::CombDialect>();
784 pass1Target.addLegalDialect<HWDialect>();
785 pass1Target.addLegalDialect<SVDialect>();
786 pass1Target.addLegalDialect<seq::SeqDialect>();
787 pass1Target.addLegalOp<WrapValidReadyOp, UnwrapValidReadyOp, WrapFIFOOp,
788 UnwrapFIFOOp>();
789 pass1Target.addLegalOp<SnoopTransactionOp, SnoopValidReadyOp>();
790
791 pass1Target.addIllegalOp<WrapSVInterfaceOp, UnwrapSVInterfaceOp>();
792 pass1Target.addIllegalOp<PipelineStageOp>();
793 pass1Target.addIllegalOp<CompressedManifestOp>();
794
795 // Add all the conversion patterns.
796 ESIHWBuilder esiBuilder(top);
797 RewritePatternSet pass1Patterns(ctxt);
798 pass1Patterns.insert<PipelineStageLowering>(esiBuilder, ctxt);
799 pass1Patterns.insert<WrapInterfaceLower>(ctxt);
800 pass1Patterns.insert<UnwrapInterfaceLower>(ctxt);
801 pass1Patterns.insert<CosimToHostLowering>(esiBuilder);
802 pass1Patterns.insert<CosimFromHostLowering>(esiBuilder);
803 pass1Patterns.insert<NullSourceOpLowering>(ctxt);
804
805 if (platform == Platform::cosim)
806 pass1Patterns.insert<CosimManifestLowering>(ctxt);
807 else if (platform == Platform::fpga)
808 pass1Patterns.insert<ManifestRomLowering>(ctxt);
809 else
810 pass1Patterns.insert<RemoveOpLowering<CompressedManifestOp>>(ctxt);
811
812 // Run the conversion.
813 if (failed(
814 applyPartialConversion(top, pass1Target, std::move(pass1Patterns)))) {
815 signalPassFailure();
816 return;
817 }
818
819 // Lower all the snoop operations.
820 ConversionTarget pass2Target(*ctxt);
821 pass2Target.addLegalDialect<comb::CombDialect>();
822 pass2Target.addLegalDialect<HWDialect>();
823 pass2Target.addLegalDialect<SVDialect>();
824 pass2Target.addIllegalOp<SnoopTransactionOp, SnoopValidReadyOp>();
825 pass2Target.addLegalOp<WrapValidReadyOp, UnwrapValidReadyOp, WrapFIFOOp,
826 UnwrapFIFOOp>();
827 RewritePatternSet pass2Patterns(ctxt);
828 pass2Patterns.insert<RemoveSnoopOp>(ctxt);
829 pass2Patterns.insert<RemoveSnoopTransactionOp>(ctxt);
830 if (failed(
831 applyPartialConversion(top, pass2Target, std::move(pass2Patterns)))) {
832 signalPassFailure();
833 return;
834 }
835
836 // Lower the channel operations.
837 ConversionTarget pass3Target(*ctxt);
838 pass3Target.addLegalDialect<comb::CombDialect>();
839 pass3Target.addLegalDialect<HWDialect>();
840 pass3Target.addLegalDialect<SVDialect>();
841 pass3Target.addIllegalDialect<ESIDialect>();
842
843 RewritePatternSet pass3Patterns(ctxt);
844 pass3Patterns.insert<CanonicalizerOpLowering<UnwrapFIFOOp>>(ctxt);
845 pass3Patterns.insert<CanonicalizerOpLowering<WrapFIFOOp>>(ctxt);
846 pass3Patterns.insert<RemoveWrapUnwrap>(ctxt);
847 if (failed(
848 applyPartialConversion(top, pass3Target, std::move(pass3Patterns))))
849 signalPassFailure();
850}
851
852std::unique_ptr<OperationPass<ModuleOp>> circt::esi::createESItoHWPass() {
853 return std::make_unique<ESItoHWPass>();
854}
AIGLongestPathObject wrap(llvm::PointerUnion< Object *, DataflowPath::OutputPort * > object)
Definition AIG.cpp:57
static EvaluatorValuePtr unwrap(OMEvaluatorValue c)
Definition OM.cpp:111
Instantiate one of these and use it to build typed backedges.
Backedge is a wrapper class around a Value.
void setValue(mlir::Value)
Assist the lowering steps for conversions which need to create auxiliary IR.
Definition PassDetails.h:56
static constexpr char validStr[]
Definition PassDetails.h:76
static constexpr char readyStr[]
Definition PassDetails.h:77
static constexpr char dataStr[]
Definition PassDetails.h:76
create(low_bit, result_type, input=None)
Definition comb.py:187
create(data_type, value)
Definition hw.py:441
create(data_type, value)
Definition hw.py:433
create(cls, result_type, reset=None, reset_value=None, name=None, sym_name=None, **kwargs)
Definition seq.py:157
create(dest, src)
Definition sv.py:98
create(value)
Definition sv.py:106
uint64_t getWidth(Type t)
Definition ESIPasses.cpp:32
StringAttr getTypeID(Type t)
Definition ESIPasses.cpp:26
std::unique_ptr< OperationPass< ModuleOp > > createESItoHWPass()
mlir::Type innerType(mlir::Type type)
Definition ESITypes.cpp:227
int64_t getBitWidth(mlir::Type type)
Return the hardware bit width of a type.
Definition HWTypes.cpp:110
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Definition esi.py:1
static constexpr char fpga[]
Definition ESIPasses.h:29
static constexpr char cosim[]
Definition ESIPasses.h:28
Generic pattern for removing an op during pattern conversion.
Definition PassDetails.h:40
This holds a decoded list of input/inout and output ports for a module or instance.
This holds the name, type, direction of a module's ports.