CIRCT  19.0.0git
IbisContainersToHW.cpp
Go to the documentation of this file.
1 //===- IbisContainersToHW.cpp ---------------------------------------------===//
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 
11 #include "mlir/Pass/Pass.h"
12 
13 #include "circt/Dialect/HW/HWOps.h"
18 
20 #include "mlir/IR/OperationSupport.h"
21 #include "mlir/Transforms/DialectConversion.h"
22 #include "llvm/ADT/TypeSwitch.h"
23 
24 namespace circt {
25 namespace ibis {
26 #define GEN_PASS_DEF_IBISCONTAINERSTOHW
27 #include "circt/Dialect/Ibis/IbisPasses.h.inc"
28 } // namespace ibis
29 } // namespace circt
30 
31 using namespace circt;
32 using namespace ibis;
33 
34 namespace {
35 
36 // Analysis result for generating the port interface of a container + a bit of
37 // port op caching.
38 struct ContainerPortInfo {
39  std::unique_ptr<hw::ModulePortInfo> hwPorts;
40 
41  // A mapping between the port name and the port op within the container.
42  llvm::DenseMap<StringAttr, InputPortOp> opInputs;
43 
44  // A mapping between the port name and the port op within the container.
45  llvm::DenseMap<StringAttr, OutputPortOp> opOutputs;
46 
47  // A mapping between port symbols and their corresponding port name.
48  llvm::DenseMap<StringAttr, StringAttr> portSymbolsToPortName;
49 
50  ContainerPortInfo() = default;
51  ContainerPortInfo(ContainerOp container) {
52  SmallVector<hw::PortInfo, 4> inputs, outputs;
53  auto *ctx = container.getContext();
54 
55  // Copies all attributes from a port, except for the port symbol, name, and
56  // type.
57  auto copyPortAttrs = [ctx](auto port) {
58  llvm::DenseSet<StringAttr> elidedAttrs;
59  elidedAttrs.insert(port.getInnerSymAttrName());
60  elidedAttrs.insert(port.getTypeAttrName());
61  elidedAttrs.insert(port.getNameAttrName());
62  llvm::SmallVector<NamedAttribute> attrs;
63  for (NamedAttribute namedAttr : port->getAttrs()) {
64  if (elidedAttrs.contains(namedAttr.getName()))
65  continue;
66  attrs.push_back(namedAttr);
67  }
68  return DictionaryAttr::get(ctx, attrs);
69  };
70 
71  // Gather in and output port ops to define the hw.module interface. Here, we
72  // also perform uniqueing of the port names.
73  Namespace portNs;
74  for (auto input : container.getBodyBlock()->getOps<InputPortOp>()) {
75  auto uniquePortName =
76  StringAttr::get(ctx, portNs.newName(input.getNameHint()));
77  opInputs[uniquePortName] = input;
78  hw::PortInfo portInfo;
79  portInfo.name = uniquePortName;
80  portSymbolsToPortName[input.getInnerSym().getSymName()] = uniquePortName;
81  portInfo.type = cast<PortOpInterface>(input.getOperation()).getPortType();
82  portInfo.dir = hw::ModulePort::Direction::Input;
83  portInfo.attrs = copyPortAttrs(input);
84  inputs.push_back(portInfo);
85  }
86 
87  for (auto output : container.getBodyBlock()->getOps<OutputPortOp>()) {
88  auto uniquePortName =
89  StringAttr::get(ctx, portNs.newName(output.getNameAttr().getValue()));
90  opOutputs[uniquePortName] = output;
91 
92  hw::PortInfo portInfo;
93  portInfo.name = uniquePortName;
94  portSymbolsToPortName[output.getInnerSym().getSymName()] = uniquePortName;
95  portInfo.type =
96  cast<PortOpInterface>(output.getOperation()).getPortType();
97  portInfo.dir = hw::ModulePort::Direction::Output;
98  portInfo.attrs = copyPortAttrs(output);
99  outputs.push_back(portInfo);
100  }
101  hwPorts = std::make_unique<hw::ModulePortInfo>(inputs, outputs);
102  }
103 };
104 
105 using ContainerPortInfoMap =
106  llvm::DenseMap<hw::InnerRefAttr, ContainerPortInfo>;
107 using ContainerHWModSymbolMap = llvm::DenseMap<hw::InnerRefAttr, StringAttr>;
108 
109 static StringAttr concatNames(mlir::StringAttr lhs, mlir::StringAttr rhs) {
110  return StringAttr::get(lhs.getContext(), lhs.strref() + "_" + rhs.strref());
111 }
112 
113 struct ContainerOpConversionPattern : public OpConversionPattern<ContainerOp> {
114  ContainerOpConversionPattern(MLIRContext *ctx, Namespace &modNamespace,
115  ContainerPortInfoMap &portOrder,
116  ContainerHWModSymbolMap &modSymMap)
117  : OpConversionPattern<ContainerOp>(ctx), modNamespace(modNamespace),
118  portOrder(portOrder), modSymMap(modSymMap) {}
119 
120  LogicalResult
121  matchAndRewrite(ContainerOp op, OpAdaptor adaptor,
122  ConversionPatternRewriter &rewriter) const override {
123  auto design = op->getParentOfType<DesignOp>();
124  rewriter.setInsertionPoint(design);
125 
126  // Generate and de-alias the hw.module name.
127  // If the container is a top level container, ignore the design name.
128  StringAttr hwmodName;
129  if (op.getIsTopLevel())
130  hwmodName = op.getNameHintAttr();
131  else
132  hwmodName =
133  concatNames(op.getInnerRef().getModule(), op.getNameHintAttr());
134 
135  hwmodName = StringAttr::get(op.getContext(),
136  modNamespace.newName(hwmodName.getValue()));
137 
138  const ContainerPortInfo &cpi = portOrder.at(op.getInnerRef());
139  auto hwMod =
140  rewriter.create<hw::HWModuleOp>(op.getLoc(), hwmodName, *cpi.hwPorts);
141  modSymMap[op.getInnerRef()] = hwMod.getSymNameAttr();
142 
143  hw::OutputOp outputOp =
144  cast<hw::OutputOp>(hwMod.getBodyBlock()->getTerminator());
145 
146  // Replace all of the reads of the inputs to use the input block arguments.
147  for (auto [idx, input] : llvm::enumerate(cpi.hwPorts->getInputs())) {
148  Value barg = hwMod.getBodyBlock()->getArgument(idx);
149  InputPortOp inputPort = cpi.opInputs.at(input.name);
150  // Replace all reads of the input port with the input block argument.
151  for (auto *user : inputPort.getOperation()->getUsers()) {
152  auto reader = dyn_cast<PortReadOp>(user);
153  if (!reader)
154  return rewriter.notifyMatchFailure(
155  user, "expected only ibis.port.read ops of the input port");
156 
157  rewriter.replaceOp(reader, barg);
158  }
159 
160  rewriter.eraseOp(inputPort);
161  }
162 
163  // Adjust the hw.output op to use ibis.port.write values
164  llvm::SmallVector<Value> outputValues;
165  for (auto [idx, output] : llvm::enumerate(cpi.hwPorts->getOutputs())) {
166  auto outputPort = cpi.opOutputs.at(output.name);
167  // Locate the write to the output op.
168  auto users = outputPort->getUsers();
169  size_t nUsers = std::distance(users.begin(), users.end());
170  if (nUsers != 1)
171  return outputPort->emitOpError()
172  << "expected exactly one ibis.port.write op of the output "
173  "port: "
174  << output.name.str() << " found: " << nUsers;
175  auto writer = cast<PortWriteOp>(*users.begin());
176  outputValues.push_back(writer.getValue());
177  rewriter.eraseOp(outputPort);
178  rewriter.eraseOp(writer);
179  }
180 
181  rewriter.mergeBlocks(&op.getBodyRegion().front(), hwMod.getBodyBlock());
182 
183  // Rewrite the hw.output op.
184  rewriter.eraseOp(outputOp);
185  rewriter.setInsertionPointToEnd(hwMod.getBodyBlock());
186  outputOp = rewriter.create<hw::OutputOp>(op.getLoc(), outputValues);
187  rewriter.eraseOp(op);
188  return success();
189  }
190 
191  Namespace &modNamespace;
192  ContainerPortInfoMap &portOrder;
193  ContainerHWModSymbolMap &modSymMap;
194 };
195 
196 struct ThisOpConversionPattern : public OpConversionPattern<ThisOp> {
197  ThisOpConversionPattern(MLIRContext *ctx)
198  : OpConversionPattern<ThisOp>(ctx) {}
199 
200  LogicalResult
201  matchAndRewrite(ThisOp op, OpAdaptor adaptor,
202  ConversionPatternRewriter &rewriter) const override {
203  // TODO: remove this op from the dialect - not needed anymore.
204  rewriter.eraseOp(op);
205  return success();
206  }
207 };
208 
209 struct ContainerInstanceOpConversionPattern
210  : public OpConversionPattern<ContainerInstanceOp> {
211 
212  ContainerInstanceOpConversionPattern(MLIRContext *ctx,
213  ContainerPortInfoMap &portOrder,
214  ContainerHWModSymbolMap &modSymMap)
215  : OpConversionPattern<ContainerInstanceOp>(ctx), portOrder(portOrder),
216  modSymMap(modSymMap) {}
217 
218  LogicalResult
219  matchAndRewrite(ContainerInstanceOp op, OpAdaptor adaptor,
220  ConversionPatternRewriter &rewriter) const override {
221  rewriter.setInsertionPoint(op);
222  llvm::SmallVector<Value> operands;
223 
224  const ContainerPortInfo &cpi =
225  portOrder.at(op.getResult().getType().getScopeRef());
226 
227  // Gather the get_port ops that target the instance
228  llvm::DenseMap<StringAttr, PortReadOp> outputReadsToReplace;
229  llvm::DenseMap<StringAttr, PortWriteOp> inputWritesToUse;
230  llvm::SmallVector<Operation *> getPortsToErase;
231  for (auto *user : op->getUsers()) {
232  auto getPort = dyn_cast<GetPortOp>(user);
233  if (!getPort)
234  return rewriter.notifyMatchFailure(
235  user, "expected only ibis.get_port op usage of the instance");
236 
237  for (auto *user : getPort->getUsers()) {
238  auto res =
239  llvm::TypeSwitch<Operation *, LogicalResult>(user)
240  .Case<PortReadOp>([&](auto read) {
241  auto [it, inserted] = outputReadsToReplace.insert(
242  {cpi.portSymbolsToPortName.at(
243  getPort.getPortSymbolAttr().getAttr()),
244  read});
245  if (!inserted)
246  return rewriter.notifyMatchFailure(
247  read, "expected only one ibis.port.read op of the "
248  "output port");
249  return success();
250  })
251  .Case<PortWriteOp>([&](auto write) {
252  auto [it, inserted] = inputWritesToUse.insert(
253  {cpi.portSymbolsToPortName.at(
254  getPort.getPortSymbolAttr().getAttr()),
255  write});
256  if (!inserted)
257  return rewriter.notifyMatchFailure(
258  write,
259  "expected only one ibis.port.write op of the input "
260  "port");
261  return success();
262  })
263  .Default([&](auto op) {
264  return rewriter.notifyMatchFailure(
265  op, "expected only ibis.port.read or ibis.port.write ops "
266  "of the "
267  "instance");
268  });
269  if (failed(res))
270  return failure();
271  }
272  getPortsToErase.push_back(getPort);
273  }
274 
275  // Grab the operands in the order of the hw.module ports.
276  size_t nInputPorts = std::distance(cpi.hwPorts->getInputs().begin(),
277  cpi.hwPorts->getInputs().end());
278  if (nInputPorts != inputWritesToUse.size()) {
279  std::string errMsg;
280  llvm::raw_string_ostream ers(errMsg);
281  ers << "Error when lowering instance ";
282  op.print(ers, mlir::OpPrintingFlags().printGenericOpForm());
283 
284  ers << "\nexpected exactly one ibis.port.write op of each input port. "
285  "Mising port assignments were:\n";
286  for (auto input : cpi.hwPorts->getInputs()) {
287  if (inputWritesToUse.find(input.name) == inputWritesToUse.end())
288  ers << "\t" << input.name << "\n";
289  }
290  return rewriter.notifyMatchFailure(op, errMsg);
291  }
292  for (auto input : cpi.hwPorts->getInputs()) {
293  auto writeOp = inputWritesToUse.at(input.name);
294  operands.push_back(writeOp.getValue());
295  rewriter.eraseOp(writeOp);
296  }
297 
298  // Determine the result types.
299  llvm::SmallVector<Type> retTypes;
300  for (auto output : cpi.hwPorts->getOutputs())
301  retTypes.push_back(output.type);
302 
303  // Gather arg and res names
304  // TODO: @mortbopet - this should be part of ModulePortInfo
305  llvm::SmallVector<Attribute> argNames, resNames;
306  llvm::transform(cpi.hwPorts->getInputs(), std::back_inserter(argNames),
307  [](auto port) { return port.name; });
308  llvm::transform(cpi.hwPorts->getOutputs(), std::back_inserter(resNames),
309  [](auto port) { return port.name; });
310 
311  // Create the hw.instance op.
312  StringRef moduleName = modSymMap[op.getTargetNameAttr()];
313  auto hwInst = rewriter.create<hw::InstanceOp>(
314  op.getLoc(), retTypes, op.getInnerSym().getSymName(), moduleName,
315  operands, rewriter.getArrayAttr(argNames),
316  rewriter.getArrayAttr(resNames),
317  /*parameters*/ rewriter.getArrayAttr({}), /*innerSym*/ nullptr);
318 
319  // Replace the reads of the output ports with the hw.instance results.
320  for (auto [output, value] :
321  llvm::zip(cpi.hwPorts->getOutputs(), hwInst.getResults())) {
322  auto outputReadIt = outputReadsToReplace.find(output.name);
323  if (outputReadIt == outputReadsToReplace.end())
324  continue;
325  // TODO: RewriterBase::replaceAllUsesWith is not currently supported by
326  // DialectConversion. Using it may lead to assertions about mutating
327  // replaced/erased ops. For now, do this RAUW directly, until
328  // ConversionPatternRewriter properly supports RAUW.
329  // See https://github.com/llvm/circt/issues/6795.
330  outputReadIt->second.getResult().replaceAllUsesWith(value);
331  rewriter.eraseOp(outputReadIt->second);
332  }
333 
334  // Erase the get_port ops.
335  for (auto *getPort : getPortsToErase)
336  rewriter.eraseOp(getPort);
337 
338  // And finally erase the instance op.
339  rewriter.eraseOp(op);
340  return success();
341  }
342 
343  ContainerPortInfoMap &portOrder;
344  ContainerHWModSymbolMap &modSymMap;
345 }; // namespace
346 
347 struct ContainersToHWPass
348  : public circt::ibis::impl::IbisContainersToHWBase<ContainersToHWPass> {
349  void runOnOperation() override;
350 };
351 } // anonymous namespace
352 
353 void ContainersToHWPass::runOnOperation() {
354  auto *ctx = &getContext();
355 
356  // Generate module signatures.
357  ContainerPortInfoMap portOrder;
358  for (auto design : getOperation().getOps<DesignOp>())
359  for (auto container : design.getOps<ContainerOp>())
360  portOrder.try_emplace(container.getInnerRef(),
361  ContainerPortInfo(container));
362 
363  ConversionTarget target(*ctx);
364  ContainerHWModSymbolMap modSymMap;
365  SymbolCache modSymCache;
366  modSymCache.addDefinitions(getOperation());
367  Namespace modNamespace;
368  modNamespace.add(modSymCache);
369  target.addIllegalOp<ContainerOp, ContainerInstanceOp, ThisOp>();
370  target.markUnknownOpDynamicallyLegal([](Operation *) { return true; });
371 
372  // Parts of the conversion patterns will update operations in place, which in
373  // turn requires the updated operations to be legalizeable. These in-place ops
374  // also include ibis ops that eventually will get replaced once all of the
375  // patterns apply.
376  target.addLegalDialect<IbisDialect>();
377 
378  RewritePatternSet patterns(ctx);
379  patterns.add<ContainerOpConversionPattern>(ctx, modNamespace, portOrder,
380  modSymMap);
381  patterns.add<ContainerInstanceOpConversionPattern>(ctx, portOrder, modSymMap);
382  patterns.add<ThisOpConversionPattern>(ctx);
383 
384  if (failed(
385  applyPartialConversion(getOperation(), target, std::move(patterns))))
386  signalPassFailure();
387 
388  // Delete empty design ops.
389  for (auto design :
390  llvm::make_early_inc_range(getOperation().getOps<DesignOp>()))
391  if (design.getBody().front().empty())
392  design.erase();
393 }
394 
395 std::unique_ptr<Pass> circt::ibis::createContainersToHWPass() {
396  return std::make_unique<ContainersToHWPass>();
397 }
static PortInfo getPort(ModuleTy &mod, size_t idx)
Definition: HWOps.cpp:1434
@ Input
Definition: HW.h:35
@ Output
Definition: HW.h:35
A namespace that is used to store existing names and generate new names in some scope within the IR.
Definition: Namespace.h:30
void add(mlir::ModuleOp module)
Definition: Namespace.h:46
StringRef newName(const Twine &name)
Return a unique name, derived from the input name, and add the new name to the internal namespace.
Definition: Namespace.h:72
void addDefinitions(mlir::Operation *top)
Populate the symbol cache with all symbol-defining operations within the 'top' operation.
Definition: SymCache.cpp:23
Default symbol cache implementation; stores associations between names (StringAttr's) to mlir::Operat...
Definition: SymCache.h:85
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
Definition: CalyxOps.cpp:54
std::unique_ptr< mlir::Pass > createContainersToHWPass()
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Definition: DebugAnalysis.h:21