CIRCT  18.0.0git
HWToSystemC.cpp
Go to the documentation of this file.
1 //===- HWToSystemC.cpp - HW To SystemC Conversion Pass --------------------===//
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 // This is the main HW to SystemC Conversion Pass Implementation.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "../PassDetail.h"
16 #include "circt/Dialect/HW/HWOps.h"
18 #include "mlir/Dialect/EmitC/IR/EmitC.h"
19 #include "mlir/IR/BuiltinDialect.h"
20 #include "mlir/Transforms/DialectConversion.h"
21 #include "llvm/ADT/TypeSwitch.h"
22 
23 using namespace mlir;
24 using namespace circt;
25 using namespace hw;
26 using namespace systemc;
27 
28 //===----------------------------------------------------------------------===//
29 // Operation Conversion Patterns
30 //===----------------------------------------------------------------------===//
31 
32 namespace {
33 
34 /// This works on each HW module, creates corresponding SystemC modules, moves
35 /// the body of the module into the new SystemC module by splitting up the body
36 /// into field declarations, initializations done in a newly added systemc.ctor,
37 /// and internal methods to be registered in the constructor.
38 struct ConvertHWModule : public OpConversionPattern<HWModuleOp> {
39  using OpConversionPattern::OpConversionPattern;
40 
41  LogicalResult
42  matchAndRewrite(HWModuleOp module, OpAdaptor adaptor,
43  ConversionPatternRewriter &rewriter) const override {
44  // Parameterized modules are supported yet.
45  if (!module.getParameters().empty())
46  return emitError(module->getLoc(), "module parameters not supported yet");
47 
48  auto ports = module.getPortList();
49  if (llvm::any_of(ports, [](auto &port) { return port.isInOut(); }))
50  return emitError(module->getLoc(), "inout arguments not supported yet");
51 
52  // Create the SystemC module.
53  for (size_t i = 0; i < ports.size(); ++i)
54  ports.at(i).type = typeConverter->convertType(ports.at(i).type);
55 
56  auto scModule = rewriter.create<SCModuleOp>(module.getLoc(),
57  module.getNameAttr(), ports);
58  auto *outputOp = module.getBodyBlock()->getTerminator();
59  scModule.setVisibility(module.getVisibility());
60 
61  auto portAttrs = module.getAllPortAttrs();
62  scModule.setAllArgAttrs(portAttrs);
63 
64  // Create a systemc.func operation inside the module after the ctor.
65  // TODO: implement logic to extract a better name and properly unique it.
66  rewriter.setInsertionPointToStart(scModule.getBodyBlock());
67  auto scFunc = rewriter.create<SCFuncOp>(
68  module.getLoc(), rewriter.getStringAttr("innerLogic"));
69 
70  // Inline the HW module body into the systemc.func body.
71  // TODO: do some dominance analysis to detect use-before-def and cycles in
72  // the use chain, which are allowed in graph regions but not in SSACFG
73  // regions, and when possible fix them.
74  scFunc.getBodyBlock()->erase();
75  Region &scFuncBody = scFunc.getBody();
76  rewriter.inlineRegionBefore(module.getBody(), scFuncBody, scFuncBody.end());
77 
78  // Register the systemc.func inside the systemc.ctor
79  rewriter.setInsertionPointToStart(
80  scModule.getOrCreateCtor().getBodyBlock());
81  rewriter.create<MethodOp>(scModule.getLoc(), scFunc.getHandle());
82 
83  // Register the sensitivities of above SC_METHOD registration.
84  SmallVector<Value> sensitivityValues(
85  llvm::make_filter_range(scModule.getArguments(), [](BlockArgument arg) {
86  return !arg.getType().isa<OutputType>();
87  }));
88  if (!sensitivityValues.empty())
89  rewriter.create<SensitiveOp>(scModule.getLoc(), sensitivityValues);
90 
91  // Move the block arguments of the systemc.func (that we got from the
92  // hw.module) to the systemc.module
93  rewriter.setInsertionPointToStart(scFunc.getBodyBlock());
94  auto portsLocal = module.getPortList();
95  for (size_t i = 0, e = scFunc.getRegion().getNumArguments(); i < e; ++i) {
96  auto inputRead =
97  rewriter
98  .create<SignalReadOp>(scFunc.getLoc(), scModule.getArgument(i))
99  .getResult();
100  auto converted = typeConverter->materializeSourceConversion(
101  rewriter, scModule.getLoc(), portsLocal.at(i).type, inputRead);
102  scFuncBody.getArgument(0).replaceAllUsesWith(converted);
103  scFuncBody.eraseArgument(0);
104  }
105 
106  // Erase the HW module.
107  rewriter.eraseOp(module);
108 
109  SmallVector<Value> outPorts;
110  for (auto val : scModule.getArguments()) {
111  if (val.getType().isa<OutputType>())
112  outPorts.push_back(val);
113  }
114 
115  rewriter.setInsertionPoint(outputOp);
116  for (auto args : llvm::zip(outPorts, outputOp->getOperands())) {
117  Value portValue = std::get<0>(args);
118  auto converted = typeConverter->materializeTargetConversion(
119  rewriter, scModule.getLoc(), getSignalBaseType(portValue.getType()),
120  std::get<1>(args));
121  rewriter.create<SignalWriteOp>(outputOp->getLoc(), portValue, converted);
122  }
123 
124  // Erase the HW OutputOp.
125  outputOp->dropAllReferences();
126  rewriter.eraseOp(outputOp);
127 
128  return success();
129  }
130 };
131 
132 /// Convert hw.instance operations to systemc.instance.decl and a
133 /// systemc.instance.bind_port operation for each port in the constructor. Also
134 /// insert the necessary intermediate signals and write or read their state in
135 /// the update function accordingly.
136 class ConvertInstance : public OpConversionPattern<InstanceOp> {
137  using OpConversionPattern::OpConversionPattern;
138 
139 private:
140  template <typename PortTy>
141  LogicalResult
142  collectPortInfo(ValueRange ports, ArrayAttr portNames,
143  SmallVector<systemc::ModuleType::PortInfo> &portInfo) const {
144  for (auto inPort : llvm::zip(ports, portNames)) {
145  Type ty = std::get<0>(inPort).getType();
146  systemc::ModuleType::PortInfo info;
147 
148  if (ty.isa<hw::InOutType>())
149  return failure();
150 
151  info.type = typeConverter->convertType(PortTy::get(ty));
152  info.name = std::get<1>(inPort).cast<StringAttr>();
153  portInfo.push_back(info);
154  }
155 
156  return success();
157  }
158 
159 public:
160  LogicalResult
161  matchAndRewrite(InstanceOp instanceOp, OpAdaptor adaptor,
162  ConversionPatternRewriter &rewriter) const override {
163  // Make sure the parent is already converted such that we already have a
164  // constructor and update function to insert operations into.
165  auto scModule = instanceOp->getParentOfType<SCModuleOp>();
166  if (!scModule)
167  return rewriter.notifyMatchFailure(instanceOp,
168  "parent was not an SCModuleOp");
169 
170  // Get the builders for the different places to insert operations.
171  auto ctor = scModule.getOrCreateCtor();
172  OpBuilder stateBuilder(ctor);
173  OpBuilder initBuilder = OpBuilder::atBlockEnd(ctor.getBodyBlock());
174 
175  // Collect the port types and names of the instantiated module and convert
176  // them to appropriate systemc types.
177  SmallVector<systemc::ModuleType::PortInfo> portInfo;
178  if (failed(collectPortInfo<InputType>(adaptor.getInputs(),
179  adaptor.getArgNames(), portInfo)) ||
180  failed(collectPortInfo<OutputType>(instanceOp->getResults(),
181  adaptor.getResultNames(), portInfo)))
182  return instanceOp->emitOpError("inout ports not supported");
183 
184  Location loc = instanceOp->getLoc();
185  auto instanceName = instanceOp.getInstanceNameAttr();
186  auto instModuleName = instanceOp.getModuleNameAttr();
187 
188  // Declare the instance.
189  auto instDecl = stateBuilder.create<InstanceDeclOp>(
190  loc, instanceName, instModuleName, portInfo);
191 
192  // Bind the input ports.
193  for (size_t i = 0, numInputs = adaptor.getInputs().size(); i < numInputs;
194  ++i) {
195  Value input = adaptor.getInputs()[i];
196  auto portId = rewriter.getIndexAttr(i);
197  StringAttr signalName = rewriter.getStringAttr(
198  instanceName.getValue() + "_" + portInfo[i].name.getValue());
199 
200  if (auto readOp = input.getDefiningOp<SignalReadOp>()) {
201  // Use the read channel directly without adding an
202  // intermediate signal.
203  initBuilder.create<BindPortOp>(loc, instDecl, portId,
204  readOp.getInput());
205  continue;
206  }
207 
208  // Otherwise, create an intermediate signal to bind the instance port to.
209  Type sigType = SignalType::get(getSignalBaseType(portInfo[i].type));
210  Value channel = stateBuilder.create<SignalOp>(loc, sigType, signalName);
211  initBuilder.create<BindPortOp>(loc, instDecl, portId, channel);
212  rewriter.create<SignalWriteOp>(loc, channel, input);
213  }
214 
215  // Bind the output ports.
216  for (size_t i = 0, numOutputs = instanceOp->getNumResults(); i < numOutputs;
217  ++i) {
218  size_t numInputs = adaptor.getInputs().size();
219  Value output = instanceOp->getResult(i);
220  auto portId = rewriter.getIndexAttr(i + numInputs);
221  StringAttr signalName =
222  rewriter.getStringAttr(instanceName.getValue() + "_" +
223  portInfo[i + numInputs].name.getValue());
224 
225  if (output.hasOneUse()) {
226  if (auto writeOp = dyn_cast<SignalWriteOp>(*output.user_begin())) {
227  // Use the channel written to directly. When there are multiple
228  // channels this value is written to or it is used somewhere else, we
229  // cannot shortcut it and have to insert an intermediate value because
230  // we cannot insert multiple bind statements for one submodule port.
231  // It is also necessary to bind it to an intermediate signal when it
232  // has no uses as every port has to be bound to a channel.
233  initBuilder.create<BindPortOp>(loc, instDecl, portId,
234  writeOp.getDest());
235  writeOp->erase();
236  continue;
237  }
238  }
239 
240  // Otherwise, create an intermediate signal.
241  Type sigType =
242  SignalType::get(getSignalBaseType(portInfo[i + numInputs].type));
243  Value channel = stateBuilder.create<SignalOp>(loc, sigType, signalName);
244  initBuilder.create<BindPortOp>(loc, instDecl, portId, channel);
245  auto instOut = rewriter.create<SignalReadOp>(loc, channel);
246  output.replaceAllUsesWith(instOut);
247  }
248 
249  rewriter.eraseOp(instanceOp);
250  return success();
251  }
252 };
253 
254 } // namespace
255 
256 //===----------------------------------------------------------------------===//
257 // Conversion Infrastructure
258 //===----------------------------------------------------------------------===//
259 
260 static void populateLegality(ConversionTarget &target) {
261  target.addIllegalDialect<HWDialect>();
262  target.addLegalDialect<mlir::BuiltinDialect>();
263  target.addLegalDialect<systemc::SystemCDialect>();
264  target.addLegalDialect<comb::CombDialect>();
265  target.addLegalDialect<emitc::EmitCDialect>();
266  target.addLegalOp<hw::ConstantOp>();
267 }
268 
269 static void populateOpConversion(RewritePatternSet &patterns,
270  TypeConverter &typeConverter) {
271  patterns.add<ConvertHWModule, ConvertInstance>(typeConverter,
272  patterns.getContext());
273 }
274 
275 static void populateTypeConversion(TypeConverter &converter) {
276  converter.addConversion([](Type type) { return type; });
277  converter.addConversion([&](SignalType type) {
278  return SignalType::get(converter.convertType(type.getBaseType()));
279  });
280  converter.addConversion([&](InputType type) {
281  return InputType::get(converter.convertType(type.getBaseType()));
282  });
283  converter.addConversion([&](systemc::InOutType type) {
284  return systemc::InOutType::get(converter.convertType(type.getBaseType()));
285  });
286  converter.addConversion([&](OutputType type) {
287  return OutputType::get(converter.convertType(type.getBaseType()));
288  });
289  converter.addConversion([](IntegerType type) -> Type {
290  auto bw = type.getIntOrFloatBitWidth();
291  if (bw == 1)
292  return type;
293 
294  if (bw <= 64) {
295  if (type.isSigned())
296  return systemc::IntType::get(type.getContext(), bw);
297 
298  return UIntType::get(type.getContext(), bw);
299  }
300 
301  if (bw <= 512) {
302  if (type.isSigned())
303  return BigIntType::get(type.getContext(), bw);
304 
305  return BigUIntType::get(type.getContext(), bw);
306  }
307 
308  return BitVectorType::get(type.getContext(), bw);
309  });
310 
311  converter.addSourceMaterialization(
312  [](OpBuilder &builder, Type type, ValueRange values, Location loc) {
313  assert(values.size() == 1);
314  auto op = builder.create<ConvertOp>(loc, type, values[0]);
315  return op.getResult();
316  });
317 
318  converter.addTargetMaterialization(
319  [](OpBuilder &builder, Type type, ValueRange values, Location loc) {
320  assert(values.size() == 1);
321  auto op = builder.create<ConvertOp>(loc, type, values[0]);
322  return op.getResult();
323  });
324 }
325 
326 //===----------------------------------------------------------------------===//
327 // HW to SystemC Conversion Pass
328 //===----------------------------------------------------------------------===//
329 
330 namespace {
331 struct HWToSystemCPass : public ConvertHWToSystemCBase<HWToSystemCPass> {
332  void runOnOperation() override;
333 };
334 } // namespace
335 
336 /// Create a HW to SystemC dialects conversion pass.
337 std::unique_ptr<OperationPass<ModuleOp>> circt::createConvertHWToSystemCPass() {
338  return std::make_unique<HWToSystemCPass>();
339 }
340 
341 /// This is the main entrypoint for the HW to SystemC conversion pass.
342 void HWToSystemCPass::runOnOperation() {
343  MLIRContext &context = getContext();
344  ModuleOp module = getOperation();
345 
346  // Create the include operation here to have exactly one 'systemc' include at
347  // the top instead of one per module.
348  OpBuilder builder(module.getRegion());
349  builder.create<emitc::IncludeOp>(module->getLoc(), "systemc.h", true);
350 
351  ConversionTarget target(context);
352  TypeConverter typeConverter;
353  RewritePatternSet patterns(&context);
354  populateLegality(target);
355  populateTypeConversion(typeConverter);
356  populateOpConversion(patterns, typeConverter);
357 
358  if (failed(applyFullConversion(module, target, std::move(patterns))))
359  signalPassFailure();
360 }
assert(baseType &&"element must be base type")
static void populateLegality(ConversionTarget &target)
static void populateOpConversion(RewritePatternSet &patterns, TypeConverter &typeConverter)
static void populateTypeConversion(TypeConverter &converter)
Builder builder
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
Definition: CalyxOps.cpp:53
circt::hw::InOutType InOutType
Definition: SVTypes.h:25
Type getSignalBaseType(Type type)
Get the type wrapped by a signal or port (in, inout, out) type.
This file defines an intermediate representation for circuits acting as an abstraction for constraint...
std::unique_ptr< mlir::OperationPass< mlir::ModuleOp > > createConvertHWToSystemCPass()
Create a HW to SystemC dialects conversion pass.
Definition: hw.py:1