CIRCT  19.0.0git
HandshakeToHW.cpp
Go to the documentation of this file.
1 //===- HandshakeToHW.cpp - Translate Handshake into HW ------------===//
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 Handshake to HW Conversion Pass Implementation.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "../PassDetail.h"
17 #include "circt/Dialect/HW/HWOps.h"
25 #include "mlir/Dialect/Arith/IR/Arith.h"
26 #include "mlir/Dialect/MemRef/IR/MemRef.h"
27 #include "mlir/IR/ImplicitLocOpBuilder.h"
28 #include "mlir/Pass/PassManager.h"
29 #include "mlir/Transforms/DialectConversion.h"
30 #include "llvm/ADT/TypeSwitch.h"
31 #include "llvm/Support/MathExtras.h"
32 #include <optional>
33 
34 using namespace mlir;
35 using namespace circt;
36 using namespace circt::handshake;
37 using namespace circt::hw;
38 
39 using NameUniquer = std::function<std::string(Operation *)>;
40 
41 namespace {
42 
43 static Type tupleToStruct(TypeRange types) {
44  return toValidType(mlir::TupleType::get(types[0].getContext(), types));
45 }
46 
47 // Shared state used by various functions; captured in a struct to reduce the
48 // number of arguments that we have to pass around.
49 struct HandshakeLoweringState {
50  ModuleOp parentModule;
51  NameUniquer nameUniquer;
52 };
53 
54 // A type converter is needed to perform the in-flight materialization of "raw"
55 // (non-ESI channel) types to their ESI channel correspondents. This comes into
56 // effect when backedges exist in the input IR.
57 class ESITypeConverter : public TypeConverter {
58 public:
59  ESITypeConverter() {
60  addConversion([](Type type) -> Type { return esiWrapper(type); });
61 
62  addTargetMaterialization(
63  [&](mlir::OpBuilder &builder, mlir::Type resultType,
64  mlir::ValueRange inputs,
65  mlir::Location loc) -> std::optional<mlir::Value> {
66  if (inputs.size() != 1)
67  return std::nullopt;
68  return inputs[0];
69  });
70 
71  addSourceMaterialization(
72  [&](mlir::OpBuilder &builder, mlir::Type resultType,
73  mlir::ValueRange inputs,
74  mlir::Location loc) -> std::optional<mlir::Value> {
75  if (inputs.size() != 1)
76  return std::nullopt;
77  return inputs[0];
78  });
79  }
80 };
81 
82 } // namespace
83 
84 /// Returns a submodule name resulting from an operation, without discriminating
85 /// type information.
86 static std::string getBareSubModuleName(Operation *oldOp) {
87  // The dialect name is separated from the operation name by '.', which is not
88  // valid in SystemVerilog module names. In case this name is used in
89  // SystemVerilog output, replace '.' with '_'.
90  std::string subModuleName = oldOp->getName().getStringRef().str();
91  std::replace(subModuleName.begin(), subModuleName.end(), '.', '_');
92  return subModuleName;
93 }
94 
95 static std::string getCallName(Operation *op) {
96  auto callOp = dyn_cast<handshake::InstanceOp>(op);
97  return callOp ? callOp.getModule().str() : getBareSubModuleName(op);
98 }
99 
100 /// Extracts the type of the data-carrying type of opType. If opType is an ESI
101 /// channel, getHandshakeBundleDataType extracts the data-carrying type, else,
102 /// assume that opType itself is the data-carrying type.
103 static Type getOperandDataType(Value op) {
104  auto opType = op.getType();
105  if (auto channelType = opType.dyn_cast<esi::ChannelType>())
106  return channelType.getInner();
107  return opType;
108 }
109 
110 /// Filters NoneType's from the input.
111 static SmallVector<Type> filterNoneTypes(ArrayRef<Type> input) {
112  SmallVector<Type> filterRes;
113  llvm::copy_if(input, std::back_inserter(filterRes),
114  [](Type type) { return !type.isa<NoneType>(); });
115  return filterRes;
116 }
117 
118 /// Returns a set of types which may uniquely identify the provided op. Return
119 /// value is <inputTypes, outputTypes>.
120 using DiscriminatingTypes = std::pair<SmallVector<Type>, SmallVector<Type>>;
122  return TypeSwitch<Operation *, DiscriminatingTypes>(op)
123  .Case<MemoryOp, ExternalMemoryOp>([&](auto memOp) {
124  return DiscriminatingTypes{{},
125  {memOp.getMemRefType().getElementType()}};
126  })
127  .Default([&](auto) {
128  // By default, all in- and output types which is not a control type
129  // (NoneType) are discriminating types.
130  std::vector<Type> inTypes, outTypes;
131  llvm::transform(op->getOperands(), std::back_inserter(inTypes),
133  llvm::transform(op->getResults(), std::back_inserter(outTypes),
135  return DiscriminatingTypes{filterNoneTypes(inTypes),
136  filterNoneTypes(outTypes)};
137  });
138 }
139 
140 /// Get type name. Currently we only support integer or index types.
141 /// The emitted type aligns with the getFIRRTLType() method. Thus all integers
142 /// other than signed integers will be emitted as unsigned.
143 // NOLINTNEXTLINE(misc-no-recursion)
144 static std::string getTypeName(Location loc, Type type) {
145  std::string typeName;
146  // Builtin types
147  if (type.isIntOrIndex()) {
148  if (auto indexType = type.dyn_cast<IndexType>())
149  typeName += "_ui" + std::to_string(indexType.kInternalStorageBitWidth);
150  else if (type.isSignedInteger())
151  typeName += "_si" + std::to_string(type.getIntOrFloatBitWidth());
152  else
153  typeName += "_ui" + std::to_string(type.getIntOrFloatBitWidth());
154  } else if (auto tupleType = type.dyn_cast<TupleType>()) {
155  typeName += "_tuple";
156  for (auto elementType : tupleType.getTypes())
157  typeName += getTypeName(loc, elementType);
158  } else if (auto structType = type.dyn_cast<hw::StructType>()) {
159  typeName += "_struct";
160  for (auto element : structType.getElements())
161  typeName += "_" + element.name.str() + getTypeName(loc, element.type);
162  } else
163  emitError(loc) << "unsupported data type '" << type << "'";
164 
165  return typeName;
166 }
167 
168 /// Construct a name for creating HW sub-module.
169 static std::string getSubModuleName(Operation *oldOp) {
170  if (auto instanceOp = dyn_cast<handshake::InstanceOp>(oldOp); instanceOp)
171  return instanceOp.getModule().str();
172 
173  std::string subModuleName = getBareSubModuleName(oldOp);
174 
175  // Add value of the constant operation.
176  if (auto constOp = dyn_cast<handshake::ConstantOp>(oldOp)) {
177  if (auto intAttr = constOp.getValue().dyn_cast<IntegerAttr>()) {
178  auto intType = intAttr.getType();
179 
180  if (intType.isSignedInteger())
181  subModuleName += "_c" + std::to_string(intAttr.getSInt());
182  else if (intType.isUnsignedInteger())
183  subModuleName += "_c" + std::to_string(intAttr.getUInt());
184  else
185  subModuleName += "_c" + std::to_string((uint64_t)intAttr.getInt());
186  } else
187  oldOp->emitError("unsupported constant type");
188  }
189 
190  // Add discriminating in- and output types.
191  auto [inTypes, outTypes] = getHandshakeDiscriminatingTypes(oldOp);
192  if (!inTypes.empty())
193  subModuleName += "_in";
194  for (auto inType : inTypes)
195  subModuleName += getTypeName(oldOp->getLoc(), inType);
196 
197  if (!outTypes.empty())
198  subModuleName += "_out";
199  for (auto outType : outTypes)
200  subModuleName += getTypeName(oldOp->getLoc(), outType);
201 
202  // Add memory ID.
203  if (auto memOp = dyn_cast<handshake::MemoryOp>(oldOp))
204  subModuleName += "_id" + std::to_string(memOp.getId());
205 
206  // Add compare kind.
207  if (auto comOp = dyn_cast<mlir::arith::CmpIOp>(oldOp))
208  subModuleName += "_" + stringifyEnum(comOp.getPredicate()).str();
209 
210  // Add buffer information.
211  if (auto bufferOp = dyn_cast<handshake::BufferOp>(oldOp)) {
212  subModuleName += "_" + std::to_string(bufferOp.getNumSlots()) + "slots";
213  if (bufferOp.isSequential())
214  subModuleName += "_seq";
215  else
216  subModuleName += "_fifo";
217 
218  if (auto initValues = bufferOp.getInitValues()) {
219  subModuleName += "_init";
220  for (const Attribute e : *initValues) {
221  assert(e.isa<IntegerAttr>());
222  subModuleName +=
223  "_" + std::to_string(e.dyn_cast<IntegerAttr>().getInt());
224  }
225  }
226  }
227 
228  // Add control information.
229  if (auto ctrlInterface = dyn_cast<handshake::ControlInterface>(oldOp);
230  ctrlInterface && ctrlInterface.isControl()) {
231  // Add some additional discriminating info for non-typed operations.
232  subModuleName += "_" + std::to_string(oldOp->getNumOperands()) + "ins_" +
233  std::to_string(oldOp->getNumResults()) + "outs";
234  subModuleName += "_ctrl";
235  } else {
236  assert(
237  (!inTypes.empty() || !outTypes.empty()) &&
238  "Insufficient discriminating type info generated for the operation!");
239  }
240 
241  return subModuleName;
242 }
243 
244 //===----------------------------------------------------------------------===//
245 // HW Sub-module Related Functions
246 //===----------------------------------------------------------------------===//
247 
248 /// Check whether a submodule with the same name has been created elsewhere in
249 /// the top level module. Return the matched module operation if true, otherwise
250 /// return nullptr.
251 static HWModuleLike checkSubModuleOp(mlir::ModuleOp parentModule,
252  StringRef modName) {
253  if (auto mod = parentModule.lookupSymbol<HWModuleOp>(modName))
254  return mod;
255  if (auto mod = parentModule.lookupSymbol<HWModuleExternOp>(modName))
256  return mod;
257  return {};
258 }
259 
260 static HWModuleLike checkSubModuleOp(mlir::ModuleOp parentModule,
261  Operation *oldOp) {
262  HWModuleLike targetModule;
263  if (auto instanceOp = dyn_cast<handshake::InstanceOp>(oldOp))
264  targetModule = checkSubModuleOp(parentModule, instanceOp.getModule());
265  else
266  targetModule = checkSubModuleOp(parentModule, getSubModuleName(oldOp));
267 
268  if (isa<handshake::InstanceOp>(oldOp))
269  assert(targetModule &&
270  "handshake.instance target modules should always have been lowered "
271  "before the modules that reference them!");
272  return targetModule;
273 }
274 
275 /// Returns a vector of PortInfo's which defines the HW interface of the
276 /// to-be-converted op.
277 static ModulePortInfo getPortInfoForOp(Operation *op) {
278  return getPortInfoForOpTypes(op, op->getOperandTypes(), op->getResultTypes());
279 }
280 
281 static llvm::SmallVector<hw::detail::FieldInfo>
282 portToFieldInfo(llvm::ArrayRef<hw::PortInfo> portInfo) {
283  llvm::SmallVector<hw::detail::FieldInfo> fieldInfo;
284  for (auto port : portInfo)
285  fieldInfo.push_back({port.name, port.type});
286 
287  return fieldInfo;
288 }
289 
290 // Convert any handshake.extmemory operations and the top-level I/O
291 // associated with these.
292 static LogicalResult convertExtMemoryOps(HWModuleOp mod) {
293  auto *ctx = mod.getContext();
294 
295  // Gather memref ports to be converted.
296  llvm::DenseMap<unsigned, Value> memrefPorts;
297  for (auto [i, arg] : llvm::enumerate(mod.getBodyBlock()->getArguments())) {
298  auto channel = arg.getType().dyn_cast<esi::ChannelType>();
299  if (channel && channel.getInner().isa<MemRefType>())
300  memrefPorts[i] = arg;
301  }
302 
303  if (memrefPorts.empty())
304  return success(); // nothing to do.
305 
306  OpBuilder b(mod);
307 
308  auto getMemoryIOInfo = [&](Location loc, Twine portName, unsigned argIdx,
309  ArrayRef<hw::PortInfo> info,
310  hw::ModulePort::Direction direction) {
311  auto type = hw::StructType::get(ctx, portToFieldInfo(info));
312  auto portInfo =
313  hw::PortInfo{{b.getStringAttr(portName), type, direction}, argIdx};
314  return portInfo;
315  };
316 
317  for (auto [i, arg] : memrefPorts) {
318  // Insert ports into the module
319  auto memName = mod.getArgName(i);
320 
321  // Get the attached extmemory external module.
322  auto extmemInstance = cast<hw::InstanceOp>(*arg.getUsers().begin());
323  auto extmemMod =
324  cast<hw::HWModuleExternOp>(SymbolTable::lookupNearestSymbolFrom(
325  extmemInstance, extmemInstance.getModuleNameAttr()));
326 
327  ModulePortInfo portInfo(extmemMod.getPortList());
328 
329  // The extmemory external module's interface is a direct wrapping of the
330  // original handshake.extmemory operation in- and output types. Remove the
331  // first input argument (the !esi.channel<memref> op) since that is what
332  // we're replacing with a materialized interface.
333  portInfo.eraseInput(0);
334 
335  // Add memory input - this is the output of the extmemory op.
336  SmallVector<PortInfo> outputs(portInfo.getOutputs());
337  auto inPortInfo =
338  getMemoryIOInfo(arg.getLoc(), memName.strref() + "_in", i, outputs,
340  mod.insertPorts({{i, inPortInfo}}, {});
341  auto newInPort = mod.getArgumentForInput(i);
342  // Replace the extmemory submodule outputs with the newly created inputs.
343  b.setInsertionPointToStart(mod.getBodyBlock());
344  auto newInPortExploded = b.create<hw::StructExplodeOp>(
345  arg.getLoc(), extmemMod.getOutputTypes(), newInPort);
346  extmemInstance.replaceAllUsesWith(newInPortExploded.getResults());
347 
348  // Add memory output - this is the inputs of the extmemory op (without the
349  // first argument);
350  unsigned outArgI = mod.getNumOutputPorts();
351  SmallVector<PortInfo> inputs(portInfo.getInputs());
352  auto outPortInfo =
353  getMemoryIOInfo(arg.getLoc(), memName.strref() + "_out", outArgI,
355 
356  auto memOutputArgs = extmemInstance.getOperands().drop_front();
357  b.setInsertionPoint(mod.getBodyBlock()->getTerminator());
358  auto memOutputStruct = b.create<hw::StructCreateOp>(
359  arg.getLoc(), outPortInfo.type, memOutputArgs);
360  mod.appendOutputs({{outPortInfo.name, memOutputStruct}});
361 
362  // Erase the extmemory submodule instace since the i/o has now been
363  // plumbed.
364  extmemMod.erase();
365  extmemInstance.erase();
366 
367  // Erase the original memref argument of the top-level i/o now that it's use
368  // has been removed.
369  mod.modifyPorts(/*insertInputs*/ {}, /*insertOutputs*/ {},
370  /*eraseInputs*/ {i + 1}, /*eraseOutputs*/ {});
371  }
372 
373  return success();
374 }
375 
376 namespace {
377 
378 // Input handshakes contain a resolved valid and (optional )data signal, and
379 // a to-be-assigned ready signal.
380 struct InputHandshake {
381  Value valid;
382  std::shared_ptr<Backedge> ready;
383  Value data;
384 };
385 
386 // Output handshakes contain a resolved ready, and to-be-assigned valid and
387 // (optional) data signals.
388 struct OutputHandshake {
389  std::shared_ptr<Backedge> valid;
390  Value ready;
391  std::shared_ptr<Backedge> data;
392 };
393 
394 /// A helper struct that acts like a wire. Can be used to interact with the
395 /// RTLBuilder when multiple built components should be connected.
396 struct HandshakeWire {
397  HandshakeWire(BackedgeBuilder &bb, Type dataType) {
398  MLIRContext *ctx = dataType.getContext();
399  auto i1Type = IntegerType::get(ctx, 1);
400  valid = std::make_shared<Backedge>(bb.get(i1Type));
401  ready = std::make_shared<Backedge>(bb.get(i1Type));
402  data = std::make_shared<Backedge>(bb.get(dataType));
403  }
404 
405  // Functions that allow to treat a wire like an input or output port.
406  // **Careful**: Such a port will not be updated when backedges are resolved.
407  InputHandshake getAsInput() { return {*valid, ready, *data}; }
408  OutputHandshake getAsOutput() { return {valid, *ready, data}; }
409 
410  std::shared_ptr<Backedge> valid;
411  std::shared_ptr<Backedge> ready;
412  std::shared_ptr<Backedge> data;
413 };
414 
415 template <typename T, typename TInner>
416 llvm::SmallVector<T> extractValues(llvm::SmallVector<TInner> &container,
417  llvm::function_ref<T(TInner &)> extractor) {
418  llvm::SmallVector<T> result;
419  llvm::transform(container, std::back_inserter(result), extractor);
420  return result;
421 }
422 struct UnwrappedIO {
423  llvm::SmallVector<InputHandshake> inputs;
424  llvm::SmallVector<OutputHandshake> outputs;
425 
426  llvm::SmallVector<Value> getInputValids() {
427  return extractValues<Value, InputHandshake>(
428  inputs, [](auto &hs) { return hs.valid; });
429  }
430  llvm::SmallVector<std::shared_ptr<Backedge>> getInputReadys() {
431  return extractValues<std::shared_ptr<Backedge>, InputHandshake>(
432  inputs, [](auto &hs) { return hs.ready; });
433  }
434  llvm::SmallVector<Value> getInputDatas() {
435  return extractValues<Value, InputHandshake>(
436  inputs, [](auto &hs) { return hs.data; });
437  }
438  llvm::SmallVector<std::shared_ptr<Backedge>> getOutputValids() {
439  return extractValues<std::shared_ptr<Backedge>, OutputHandshake>(
440  outputs, [](auto &hs) { return hs.valid; });
441  }
442  llvm::SmallVector<Value> getOutputReadys() {
443  return extractValues<Value, OutputHandshake>(
444  outputs, [](auto &hs) { return hs.ready; });
445  }
446  llvm::SmallVector<std::shared_ptr<Backedge>> getOutputDatas() {
447  return extractValues<std::shared_ptr<Backedge>, OutputHandshake>(
448  outputs, [](auto &hs) { return hs.data; });
449  }
450 };
451 
452 // A class containing a bunch of syntactic sugar to reduce builder function
453 // verbosity.
454 // @todo: should be moved to support.
455 struct RTLBuilder {
456  RTLBuilder(hw::ModulePortInfo info, OpBuilder &builder, Location loc,
457  Value clk = Value(), Value rst = Value())
458  : info(std::move(info)), b(builder), loc(loc), clk(clk), rst(rst) {}
459 
460  Value constant(const APInt &apv, std::optional<StringRef> name = {}) {
461  // Cannot use zero-width APInt's in DenseMap's, see
462  // https://github.com/llvm/llvm-project/issues/58013
463  bool isZeroWidth = apv.getBitWidth() == 0;
464  if (!isZeroWidth) {
465  auto it = constants.find(apv);
466  if (it != constants.end())
467  return it->second;
468  }
469 
470  auto cval = b.create<hw::ConstantOp>(loc, apv);
471  if (!isZeroWidth)
472  constants[apv] = cval;
473  return cval;
474  }
475 
476  Value constant(unsigned width, int64_t value,
477  std::optional<StringRef> name = {}) {
478  return constant(APInt(width, value));
479  }
480  std::pair<Value, Value> wrap(Value data, Value valid,
481  std::optional<StringRef> name = {}) {
482  auto wrapOp = b.create<esi::WrapValidReadyOp>(loc, data, valid);
483  return {wrapOp.getResult(0), wrapOp.getResult(1)};
484  }
485  std::pair<Value, Value> unwrap(Value channel, Value ready,
486  std::optional<StringRef> name = {}) {
487  auto unwrapOp = b.create<esi::UnwrapValidReadyOp>(loc, channel, ready);
488  return {unwrapOp.getResult(0), unwrapOp.getResult(1)};
489  }
490 
491  // Various syntactic sugar functions.
492  Value reg(StringRef name, Value in, Value rstValue, Value clk = Value(),
493  Value rst = Value()) {
494  Value resolvedClk = clk ? clk : this->clk;
495  Value resolvedRst = rst ? rst : this->rst;
496  assert(resolvedClk &&
497  "No global clock provided to this RTLBuilder - a clock "
498  "signal must be provided to the reg(...) function.");
499  assert(resolvedRst &&
500  "No global reset provided to this RTLBuilder - a reset "
501  "signal must be provided to the reg(...) function.");
502 
503  return b.create<seq::CompRegOp>(loc, in, resolvedClk, resolvedRst, rstValue,
504  name);
505  }
506 
507  Value cmp(Value lhs, Value rhs, comb::ICmpPredicate predicate,
508  std::optional<StringRef> name = {}) {
509  return b.create<comb::ICmpOp>(loc, predicate, lhs, rhs);
510  }
511 
512  Value buildNamedOp(llvm::function_ref<Value()> f,
513  std::optional<StringRef> name) {
514  Value v = f();
515  StringAttr nameAttr;
516  Operation *op = v.getDefiningOp();
517  if (name.has_value()) {
518  op->setAttr("sv.namehint", b.getStringAttr(*name));
519  nameAttr = b.getStringAttr(*name);
520  }
521  return v;
522  }
523 
524  // Bitwise 'and'.
525  Value bAnd(ValueRange values, std::optional<StringRef> name = {}) {
526  return buildNamedOp(
527  [&]() { return b.create<comb::AndOp>(loc, values, false); }, name);
528  }
529 
530  Value bOr(ValueRange values, std::optional<StringRef> name = {}) {
531  return buildNamedOp(
532  [&]() { return b.create<comb::OrOp>(loc, values, false); }, name);
533  }
534 
535  // Bitwise 'not'.
536  Value bNot(Value value, std::optional<StringRef> name = {}) {
537  auto allOnes = constant(value.getType().getIntOrFloatBitWidth(), -1);
538  std::string inferedName;
539  if (!name) {
540  // Try to create a name from the input value.
541  if (auto valueName =
542  value.getDefiningOp()->getAttrOfType<StringAttr>("sv.namehint")) {
543  inferedName = ("not_" + valueName.getValue()).str();
544  name = inferedName;
545  }
546  }
547 
548  return buildNamedOp(
549  [&]() { return b.create<comb::XorOp>(loc, value, allOnes); }, name);
550 
551  return b.createOrFold<comb::XorOp>(loc, value, allOnes, false);
552  }
553 
554  Value shl(Value value, Value shift, std::optional<StringRef> name = {}) {
555  return buildNamedOp(
556  [&]() { return b.create<comb::ShlOp>(loc, value, shift); }, name);
557  }
558 
559  Value concat(ValueRange values, std::optional<StringRef> name = {}) {
560  return buildNamedOp([&]() { return b.create<comb::ConcatOp>(loc, values); },
561  name);
562  }
563 
564  // Packs a list of values into a hw.struct.
565  Value pack(ValueRange values, Type structType = Type(),
566  std::optional<StringRef> name = {}) {
567  if (!structType)
568  structType = tupleToStruct(values.getTypes());
569  return buildNamedOp(
570  [&]() { return b.create<hw::StructCreateOp>(loc, structType, values); },
571  name);
572  }
573 
574  // Unpacks a hw.struct into a list of values.
575  ValueRange unpack(Value value) {
576  auto structType = value.getType().cast<hw::StructType>();
577  llvm::SmallVector<Type> innerTypes;
578  structType.getInnerTypes(innerTypes);
579  return b.create<hw::StructExplodeOp>(loc, innerTypes, value).getResults();
580  }
581 
582  llvm::SmallVector<Value> toBits(Value v, std::optional<StringRef> name = {}) {
583  llvm::SmallVector<Value> bits;
584  for (unsigned i = 0, e = v.getType().getIntOrFloatBitWidth(); i != e; ++i)
585  bits.push_back(b.create<comb::ExtractOp>(loc, v, i, /*bitWidth=*/1));
586  return bits;
587  }
588 
589  // OR-reduction of the bits in 'v'.
590  Value rOr(Value v, std::optional<StringRef> name = {}) {
591  return buildNamedOp([&]() { return bOr(toBits(v)); }, name);
592  }
593 
594  // Extract bits v[hi:lo] (inclusive).
595  Value extract(Value v, unsigned lo, unsigned hi,
596  std::optional<StringRef> name = {}) {
597  unsigned width = hi - lo + 1;
598  return buildNamedOp(
599  [&]() { return b.create<comb::ExtractOp>(loc, v, lo, width); }, name);
600  }
601 
602  // Truncates 'value' to its lower 'width' bits.
603  Value truncate(Value value, unsigned width,
604  std::optional<StringRef> name = {}) {
605  return extract(value, 0, width - 1, name);
606  }
607 
608  Value zext(Value value, unsigned outWidth,
609  std::optional<StringRef> name = {}) {
610  unsigned inWidth = value.getType().getIntOrFloatBitWidth();
611  assert(inWidth <= outWidth && "zext: input width must be <- output width.");
612  if (inWidth == outWidth)
613  return value;
614  auto c0 = constant(outWidth - inWidth, 0);
615  return concat({c0, value}, name);
616  }
617 
618  Value sext(Value value, unsigned outWidth,
619  std::optional<StringRef> name = {}) {
620  return comb::createOrFoldSExt(loc, value, b.getIntegerType(outWidth), b);
621  }
622 
623  // Extracts a single bit v[bit].
624  Value bit(Value v, unsigned index, std::optional<StringRef> name = {}) {
625  return extract(v, index, index, name);
626  }
627 
628  // Creates a hw.array of the given values.
629  Value arrayCreate(ValueRange values, std::optional<StringRef> name = {}) {
630  return buildNamedOp(
631  [&]() { return b.create<hw::ArrayCreateOp>(loc, values); }, name);
632  }
633 
634  // Extract the 'index'th value from the input array.
635  Value arrayGet(Value array, Value index, std::optional<StringRef> name = {}) {
636  return buildNamedOp(
637  [&]() { return b.create<hw::ArrayGetOp>(loc, array, index); }, name);
638  }
639 
640  // Muxes a range of values.
641  // The select signal is expected to be a decimal value which selects starting
642  // from the lowest index of value.
643  Value mux(Value index, ValueRange values,
644  std::optional<StringRef> name = {}) {
645  if (values.size() == 2)
646  return b.create<comb::MuxOp>(loc, index, values[1], values[0]);
647 
648  return arrayGet(arrayCreate(values), index, name);
649  }
650 
651  // Muxes a range of values. The select signal is expected to be a 1-hot
652  // encoded value.
653  Value ohMux(Value index, ValueRange inputs) {
654  // Confirm the select input can be a one-hot encoding for the inputs.
655  unsigned numInputs = inputs.size();
656  assert(numInputs == index.getType().getIntOrFloatBitWidth() &&
657  "one-hot select can't mux inputs");
658 
659  // Start the mux tree with zero value.
660  // Todo: clean up when handshake supports i0.
661  auto dataType = inputs[0].getType();
662  unsigned width =
663  dataType.isa<NoneType>() ? 0 : dataType.getIntOrFloatBitWidth();
664  Value muxValue = constant(width, 0);
665 
666  // Iteratively chain together muxes from the high bit to the low bit.
667  for (size_t i = numInputs - 1; i != 0; --i) {
668  Value input = inputs[i];
669  Value selectBit = bit(index, i);
670  muxValue = mux(selectBit, {muxValue, input});
671  }
672 
673  return muxValue;
674  }
675 
676  hw::ModulePortInfo info;
677  OpBuilder &b;
678  Location loc;
679  Value clk, rst;
680  DenseMap<APInt, Value> constants;
681 };
682 
683 /// Creates a Value that has an assigned zero value. For structs, this
684 /// corresponds to assigning zero to each element recursively.
685 static Value createZeroDataConst(RTLBuilder &s, Location loc, Type type) {
686  return TypeSwitch<Type, Value>(type)
687  .Case<NoneType>([&](NoneType) { return s.constant(0, 0); })
688  .Case<IntType, IntegerType>([&](auto type) {
689  return s.constant(type.getIntOrFloatBitWidth(), 0);
690  })
691  .Case<hw::StructType>([&](auto structType) {
692  SmallVector<Value> zeroValues;
693  for (auto field : structType.getElements())
694  zeroValues.push_back(createZeroDataConst(s, loc, field.type));
695  return s.b.create<hw::StructCreateOp>(loc, structType, zeroValues);
696  })
697  .Default([&](Type) -> Value {
698  emitError(loc) << "unsupported type for zero value: " << type;
699  assert(false);
700  return {};
701  });
702 }
703 
704 static void
705 addSequentialIOOperandsIfNeeded(Operation *op,
706  llvm::SmallVectorImpl<Value> &operands) {
707  if (op->hasTrait<mlir::OpTrait::HasClock>()) {
708  // Parent should at this point be a hw.module and have clock and reset
709  // ports.
710  auto parent = cast<hw::HWModuleOp>(op->getParentOp());
711  operands.push_back(
712  parent.getArgumentForInput(parent.getNumInputPorts() - 2));
713  operands.push_back(
714  parent.getArgumentForInput(parent.getNumInputPorts() - 1));
715  }
716 }
717 
718 template <typename T>
719 class HandshakeConversionPattern : public OpConversionPattern<T> {
720 public:
721  HandshakeConversionPattern(ESITypeConverter &typeConverter,
722  MLIRContext *context, OpBuilder &submoduleBuilder,
723  HandshakeLoweringState &ls)
724  : OpConversionPattern<T>::OpConversionPattern(typeConverter, context),
725  submoduleBuilder(submoduleBuilder), ls(ls) {}
726 
727  using OpAdaptor = typename T::Adaptor;
728 
729  LogicalResult
730  matchAndRewrite(T op, OpAdaptor adaptor,
731  ConversionPatternRewriter &rewriter) const override {
732 
733  // Check if a submodule has already been created for the op. If so,
734  // instantiate the submodule. Else, run the pattern-defined module
735  // builder.
736  hw::HWModuleLike implModule = checkSubModuleOp(ls.parentModule, op);
737  if (!implModule) {
738  auto portInfo = ModulePortInfo(getPortInfoForOp(op));
739 
740  submoduleBuilder.setInsertionPoint(op->getParentOp());
741  implModule = submoduleBuilder.create<hw::HWModuleOp>(
742  op.getLoc(), submoduleBuilder.getStringAttr(getSubModuleName(op)),
743  portInfo, [&](OpBuilder &b, hw::HWModulePortAccessor &ports) {
744  // if 'op' has clock trait, extract these and provide them to the
745  // RTL builder.
746  Value clk, rst;
747  if (op->template hasTrait<mlir::OpTrait::HasClock>()) {
748  clk = ports.getInput("clock");
749  rst = ports.getInput("reset");
750  }
751 
752  BackedgeBuilder bb(b, op.getLoc());
753  RTLBuilder s(ports.getPortList(), b, op.getLoc(), clk, rst);
754  this->buildModule(op, bb, s, ports);
755  });
756  }
757 
758  // Instantiate the submodule.
759  llvm::SmallVector<Value> operands = adaptor.getOperands();
760  addSequentialIOOperandsIfNeeded(op, operands);
761  rewriter.replaceOpWithNewOp<hw::InstanceOp>(
762  op, implModule, rewriter.getStringAttr(ls.nameUniquer(op)), operands);
763  return success();
764  }
765 
766  virtual void buildModule(T op, BackedgeBuilder &bb, RTLBuilder &builder,
767  hw::HWModulePortAccessor &ports) const = 0;
768 
769  // Syntactic sugar functions.
770  // Unwraps an ESI-interfaced module into its constituent handshake signals.
771  // Backedges are created for the to-be-resolved signals, and output ports
772  // are assigned to their wrapped counterparts.
773  UnwrappedIO unwrapIO(RTLBuilder &s, BackedgeBuilder &bb,
774  hw::HWModulePortAccessor &ports) const {
775  UnwrappedIO unwrapped;
776  for (auto port : ports.getInputs()) {
777  if (!isa<esi::ChannelType>(port.getType()))
778  continue;
779  InputHandshake hs;
780  auto ready = std::make_shared<Backedge>(bb.get(s.b.getI1Type()));
781  auto [data, valid] = s.unwrap(port, *ready);
782  hs.data = data;
783  hs.valid = valid;
784  hs.ready = ready;
785  unwrapped.inputs.push_back(hs);
786  }
787  for (auto &outputInfo : ports.getPortList().getOutputs()) {
788  esi::ChannelType channelType =
789  dyn_cast<esi::ChannelType>(outputInfo.type);
790  if (!channelType)
791  continue;
792  OutputHandshake hs;
793  Type innerType = channelType.getInner();
794  auto data = std::make_shared<Backedge>(bb.get(innerType));
795  auto valid = std::make_shared<Backedge>(bb.get(s.b.getI1Type()));
796  auto [dataCh, ready] = s.wrap(*data, *valid);
797  hs.data = data;
798  hs.valid = valid;
799  hs.ready = ready;
800  ports.setOutput(outputInfo.name, dataCh);
801  unwrapped.outputs.push_back(hs);
802  }
803  return unwrapped;
804  }
805 
806  void setAllReadyWithCond(RTLBuilder &s, ArrayRef<InputHandshake> inputs,
807  OutputHandshake &output, Value cond) const {
808  auto validAndReady = s.bAnd({output.ready, cond});
809  for (auto &input : inputs)
810  input.ready->setValue(validAndReady);
811  }
812 
813  void buildJoinLogic(RTLBuilder &s, ArrayRef<InputHandshake> inputs,
814  OutputHandshake &output) const {
815  llvm::SmallVector<Value> valids;
816  for (auto &input : inputs)
817  valids.push_back(input.valid);
818  Value allValid = s.bAnd(valids);
819  output.valid->setValue(allValid);
820  setAllReadyWithCond(s, inputs, output, allValid);
821  }
822 
823  // Builds mux logic for the given inputs and outputs.
824  // Note: it is assumed that the caller has removed the 'select' signal from
825  // the 'unwrapped' inputs and provide it as a separate argument.
826  void buildMuxLogic(RTLBuilder &s, UnwrappedIO &unwrapped,
827  InputHandshake &select) const {
828  // ============================= Control logic =============================
829  size_t numInputs = unwrapped.inputs.size();
830  size_t selectWidth = llvm::Log2_64_Ceil(numInputs);
831  Value truncatedSelect =
832  select.data.getType().getIntOrFloatBitWidth() > selectWidth
833  ? s.truncate(select.data, selectWidth)
834  : select.data;
835 
836  // Decimal-to-1-hot decoder. 'shl' operands must be identical in size.
837  auto selectZext = s.zext(truncatedSelect, numInputs);
838  auto select1h = s.shl(s.constant(numInputs, 1), selectZext);
839  auto &res = unwrapped.outputs[0];
840 
841  // Mux input valid signals.
842  auto selectedInputValid =
843  s.mux(truncatedSelect, unwrapped.getInputValids());
844  // Result is valid when the selected input and the select input is valid.
845  auto selAndInputValid = s.bAnd({selectedInputValid, select.valid});
846  res.valid->setValue(selAndInputValid);
847  auto resValidAndReady = s.bAnd({selAndInputValid, res.ready});
848 
849  // Select is ready when result is valid and ready (result transacting).
850  select.ready->setValue(resValidAndReady);
851 
852  // Assign each input ready signal if it is currently selected.
853  for (auto [inIdx, in] : llvm::enumerate(unwrapped.inputs)) {
854  // Extract the selection bit for this input.
855  auto isSelected = s.bit(select1h, inIdx);
856 
857  // '&' that with the result valid and ready, and assign to the input
858  // ready signal.
859  auto activeAndResultValidAndReady =
860  s.bAnd({isSelected, resValidAndReady});
861  in.ready->setValue(activeAndResultValidAndReady);
862  }
863 
864  // ============================== Data logic ===============================
865  res.data->setValue(s.mux(truncatedSelect, unwrapped.getInputDatas()));
866  }
867 
868  // Builds fork logic between the single input and multiple outputs' control
869  // networks. Caller is expected to handle data separately.
870  void buildForkLogic(RTLBuilder &s, BackedgeBuilder &bb, InputHandshake &input,
871  ArrayRef<OutputHandshake> outputs) const {
872  auto c0I1 = s.constant(1, 0);
873  llvm::SmallVector<Value> doneWires;
874  for (auto [i, output] : llvm::enumerate(outputs)) {
875  auto doneBE = bb.get(s.b.getI1Type());
876  auto emitted = s.bAnd({doneBE, s.bNot(*input.ready)});
877  auto emittedReg = s.reg("emitted_" + std::to_string(i), emitted, c0I1);
878  auto outValid = s.bAnd({s.bNot(emittedReg), input.valid});
879  output.valid->setValue(outValid);
880  auto validReady = s.bAnd({output.ready, outValid});
881  auto done = s.bOr({validReady, emittedReg}, "done" + std::to_string(i));
882  doneBE.setValue(done);
883  doneWires.push_back(done);
884  }
885  input.ready->setValue(s.bAnd(doneWires, "allDone"));
886  }
887 
888  // Builds a unit-rate actor around an inner operation. 'unitBuilder' is a
889  // function which takes the set of unwrapped data inputs, and returns a
890  // value which should be assigned to the output data value.
891  void buildUnitRateJoinLogic(
892  RTLBuilder &s, UnwrappedIO &unwrappedIO,
893  llvm::function_ref<Value(ValueRange)> unitBuilder) const {
894  assert(unwrappedIO.outputs.size() == 1 &&
895  "Expected exactly one output for unit-rate join actor");
896  // Control logic.
897  this->buildJoinLogic(s, unwrappedIO.inputs, unwrappedIO.outputs[0]);
898 
899  // Data logic.
900  auto unitRes = unitBuilder(unwrappedIO.getInputDatas());
901  unwrappedIO.outputs[0].data->setValue(unitRes);
902  }
903 
904  void buildUnitRateForkLogic(
905  RTLBuilder &s, BackedgeBuilder &bb, UnwrappedIO &unwrappedIO,
906  llvm::function_ref<llvm::SmallVector<Value>(Value)> unitBuilder) const {
907  assert(unwrappedIO.inputs.size() == 1 &&
908  "Expected exactly one input for unit-rate fork actor");
909  // Control logic.
910  this->buildForkLogic(s, bb, unwrappedIO.inputs[0], unwrappedIO.outputs);
911 
912  // Data logic.
913  auto unitResults = unitBuilder(unwrappedIO.inputs[0].data);
914  assert(unitResults.size() == unwrappedIO.outputs.size() &&
915  "Expected unit builder to return one result per output");
916  for (auto [res, outport] : llvm::zip(unitResults, unwrappedIO.outputs))
917  outport.data->setValue(res);
918  }
919 
920  void buildExtendLogic(RTLBuilder &s, UnwrappedIO &unwrappedIO,
921  bool signExtend) const {
922  size_t outWidth =
923  toValidType(static_cast<Value>(*unwrappedIO.outputs[0].data).getType())
924  .getIntOrFloatBitWidth();
925  buildUnitRateJoinLogic(s, unwrappedIO, [&](ValueRange inputs) {
926  if (signExtend)
927  return s.sext(inputs[0], outWidth);
928  return s.zext(inputs[0], outWidth);
929  });
930  }
931 
932  void buildTruncateLogic(RTLBuilder &s, UnwrappedIO &unwrappedIO,
933  unsigned targetWidth) const {
934  size_t outWidth =
935  toValidType(static_cast<Value>(*unwrappedIO.outputs[0].data).getType())
936  .getIntOrFloatBitWidth();
937  buildUnitRateJoinLogic(s, unwrappedIO, [&](ValueRange inputs) {
938  return s.truncate(inputs[0], outWidth);
939  });
940  }
941 
942  /// Return the number of bits needed to index the given number of values.
943  static size_t getNumIndexBits(uint64_t numValues) {
944  return numValues > 1 ? llvm::Log2_64_Ceil(numValues) : 1;
945  }
946 
947  Value buildPriorityArbiter(RTLBuilder &s, ArrayRef<Value> inputs,
948  Value defaultValue,
949  DenseMap<size_t, Value> &indexMapping) const {
950  auto numInputs = inputs.size();
951  auto priorityArb = defaultValue;
952 
953  for (size_t i = numInputs; i > 0; --i) {
954  size_t inputIndex = i - 1;
955  size_t oneHotIndex = size_t{1} << inputIndex;
956  auto constIndex = s.constant(numInputs, oneHotIndex);
957  indexMapping[inputIndex] = constIndex;
958  priorityArb = s.mux(inputs[inputIndex], {priorityArb, constIndex});
959  }
960  return priorityArb;
961  }
962 
963 private:
964  OpBuilder &submoduleBuilder;
965  HandshakeLoweringState &ls;
966 };
967 
968 class ForkConversionPattern : public HandshakeConversionPattern<ForkOp> {
969 public:
970  using HandshakeConversionPattern<ForkOp>::HandshakeConversionPattern;
971  void buildModule(ForkOp op, BackedgeBuilder &bb, RTLBuilder &s,
972  hw::HWModulePortAccessor &ports) const override {
973  auto unwrapped = unwrapIO(s, bb, ports);
974  buildUnitRateForkLogic(s, bb, unwrapped, [&](Value input) {
975  return llvm::SmallVector<Value>(unwrapped.outputs.size(), input);
976  });
977  }
978 };
979 
980 class JoinConversionPattern : public HandshakeConversionPattern<JoinOp> {
981 public:
982  using HandshakeConversionPattern<JoinOp>::HandshakeConversionPattern;
983  void buildModule(JoinOp op, BackedgeBuilder &bb, RTLBuilder &s,
984  hw::HWModulePortAccessor &ports) const override {
985  auto unwrappedIO = unwrapIO(s, bb, ports);
986  buildJoinLogic(s, unwrappedIO.inputs, unwrappedIO.outputs[0]);
987  unwrappedIO.outputs[0].data->setValue(s.constant(0, 0));
988  };
989 };
990 
991 class SyncConversionPattern : public HandshakeConversionPattern<SyncOp> {
992 public:
993  using HandshakeConversionPattern<SyncOp>::HandshakeConversionPattern;
994  void buildModule(SyncOp op, BackedgeBuilder &bb, RTLBuilder &s,
995  hw::HWModulePortAccessor &ports) const override {
996  auto unwrappedIO = unwrapIO(s, bb, ports);
997 
998  // A helper wire that will be used to connect the two built logics
999  HandshakeWire wire(bb, s.b.getNoneType());
1000 
1001  OutputHandshake output = wire.getAsOutput();
1002  buildJoinLogic(s, unwrappedIO.inputs, output);
1003 
1004  InputHandshake input = wire.getAsInput();
1005 
1006  // The state-keeping fork logic is required here, as the circuit isn't
1007  // allowed to wait for all the consumers to be ready. Connecting the ready
1008  // signals of the outputs to their corresponding valid signals leads to
1009  // combinatorial cycles. The paper which introduced compositional dataflow
1010  // circuits explicitly mentions this limitation:
1011  // http://arcade.cs.columbia.edu/df-memocode17.pdf
1012  buildForkLogic(s, bb, input, unwrappedIO.outputs);
1013 
1014  // Directly connect the data wires, only the control signals need to be
1015  // combined.
1016  for (auto &&[in, out] : llvm::zip(unwrappedIO.inputs, unwrappedIO.outputs))
1017  out.data->setValue(in.data);
1018  };
1019 };
1020 
1021 class MuxConversionPattern : public HandshakeConversionPattern<MuxOp> {
1022 public:
1023  using HandshakeConversionPattern<MuxOp>::HandshakeConversionPattern;
1024  void buildModule(MuxOp op, BackedgeBuilder &bb, RTLBuilder &s,
1025  hw::HWModulePortAccessor &ports) const override {
1026  auto unwrappedIO = unwrapIO(s, bb, ports);
1027 
1028  // Extract select signal from the unwrapped IO.
1029  auto select = unwrappedIO.inputs[0];
1030  unwrappedIO.inputs.erase(unwrappedIO.inputs.begin());
1031  buildMuxLogic(s, unwrappedIO, select);
1032  };
1033 };
1034 
1035 class InstanceConversionPattern
1036  : public HandshakeConversionPattern<handshake::InstanceOp> {
1037 public:
1038  using HandshakeConversionPattern<
1039  handshake::InstanceOp>::HandshakeConversionPattern;
1040  void buildModule(handshake::InstanceOp op, BackedgeBuilder &bb, RTLBuilder &s,
1041  hw::HWModulePortAccessor &ports) const override {
1042  assert(false &&
1043  "If we indeed perform conversion in post-order, this "
1044  "should never be called. The base HandshakeConversionPattern logic "
1045  "will instantiate the external module.");
1046  }
1047 };
1048 
1049 class ReturnConversionPattern
1050  : public OpConversionPattern<handshake::ReturnOp> {
1051 public:
1052  using OpConversionPattern::OpConversionPattern;
1053  LogicalResult
1054  matchAndRewrite(ReturnOp op, OpAdaptor adaptor,
1055  ConversionPatternRewriter &rewriter) const override {
1056  // Locate existing output op, Append operands to output op, and move to
1057  // the end of the block.
1058  auto parent = cast<hw::HWModuleOp>(op->getParentOp());
1059  auto outputOp = *parent.getBodyBlock()->getOps<hw::OutputOp>().begin();
1060  outputOp->setOperands(adaptor.getOperands());
1061  outputOp->moveAfter(&parent.getBodyBlock()->back());
1062  rewriter.eraseOp(op);
1063  return success();
1064  }
1065 };
1066 
1067 // Converts an arbitrary operation into a unit rate actor. A unit rate actor
1068 // will transact once all inputs are valid and its output is ready.
1069 template <typename TIn, typename TOut = TIn>
1070 class UnitRateConversionPattern : public HandshakeConversionPattern<TIn> {
1071 public:
1072  using HandshakeConversionPattern<TIn>::HandshakeConversionPattern;
1073  void buildModule(TIn op, BackedgeBuilder &bb, RTLBuilder &s,
1074  hw::HWModulePortAccessor &ports) const override {
1075  auto unwrappedIO = this->unwrapIO(s, bb, ports);
1076  this->buildUnitRateJoinLogic(s, unwrappedIO, [&](ValueRange inputs) {
1077  // Create TOut - it is assumed that TOut trivially
1078  // constructs from the input data signals of TIn.
1079  // To disambiguate ambiguous builders with default arguments (e.g.,
1080  // twoState UnitAttr), specify attribute array explicitly.
1081  return s.b.create<TOut>(op.getLoc(), inputs,
1082  /* attributes */ ArrayRef<NamedAttribute>{});
1083  });
1084  };
1085 };
1086 
1087 class PackConversionPattern : public HandshakeConversionPattern<PackOp> {
1088 public:
1089  using HandshakeConversionPattern<PackOp>::HandshakeConversionPattern;
1090  void buildModule(PackOp op, BackedgeBuilder &bb, RTLBuilder &s,
1091  hw::HWModulePortAccessor &ports) const override {
1092  auto unwrappedIO = unwrapIO(s, bb, ports);
1093  buildUnitRateJoinLogic(s, unwrappedIO,
1094  [&](ValueRange inputs) { return s.pack(inputs); });
1095  };
1096 };
1097 
1098 class StructCreateConversionPattern
1099  : public HandshakeConversionPattern<hw::StructCreateOp> {
1100 public:
1101  using HandshakeConversionPattern<
1102  hw::StructCreateOp>::HandshakeConversionPattern;
1103  void buildModule(hw::StructCreateOp op, BackedgeBuilder &bb, RTLBuilder &s,
1104  hw::HWModulePortAccessor &ports) const override {
1105  auto unwrappedIO = unwrapIO(s, bb, ports);
1106  auto structType = op.getResult().getType();
1107  buildUnitRateJoinLogic(s, unwrappedIO, [&](ValueRange inputs) {
1108  return s.pack(inputs, structType);
1109  });
1110  };
1111 };
1112 
1113 class UnpackConversionPattern : public HandshakeConversionPattern<UnpackOp> {
1114 public:
1115  using HandshakeConversionPattern<UnpackOp>::HandshakeConversionPattern;
1116  void buildModule(UnpackOp op, BackedgeBuilder &bb, RTLBuilder &s,
1117  hw::HWModulePortAccessor &ports) const override {
1118  auto unwrappedIO = unwrapIO(s, bb, ports);
1119  buildUnitRateForkLogic(s, bb, unwrappedIO,
1120  [&](Value input) { return s.unpack(input); });
1121  };
1122 };
1123 
1124 class ConditionalBranchConversionPattern
1125  : public HandshakeConversionPattern<ConditionalBranchOp> {
1126 public:
1127  using HandshakeConversionPattern<
1128  ConditionalBranchOp>::HandshakeConversionPattern;
1129  void buildModule(ConditionalBranchOp op, BackedgeBuilder &bb, RTLBuilder &s,
1130  hw::HWModulePortAccessor &ports) const override {
1131  auto unwrappedIO = unwrapIO(s, bb, ports);
1132  auto cond = unwrappedIO.inputs[0];
1133  auto arg = unwrappedIO.inputs[1];
1134  auto trueRes = unwrappedIO.outputs[0];
1135  auto falseRes = unwrappedIO.outputs[1];
1136 
1137  auto condArgValid = s.bAnd({cond.valid, arg.valid});
1138 
1139  // Connect valid signal of both results.
1140  trueRes.valid->setValue(s.bAnd({cond.data, condArgValid}));
1141  falseRes.valid->setValue(s.bAnd({s.bNot(cond.data), condArgValid}));
1142 
1143  // Connecte data signals of both results.
1144  trueRes.data->setValue(arg.data);
1145  falseRes.data->setValue(arg.data);
1146 
1147  // Connect ready signal of input and condition.
1148  auto selectedResultReady =
1149  s.mux(cond.data, {falseRes.ready, trueRes.ready});
1150  auto condArgReady = s.bAnd({selectedResultReady, condArgValid});
1151  arg.ready->setValue(condArgReady);
1152  cond.ready->setValue(condArgReady);
1153  };
1154 };
1155 
1156 template <typename TIn, bool signExtend>
1157 class ExtendConversionPattern : public HandshakeConversionPattern<TIn> {
1158 public:
1159  using HandshakeConversionPattern<TIn>::HandshakeConversionPattern;
1160  void buildModule(TIn op, BackedgeBuilder &bb, RTLBuilder &s,
1161  hw::HWModulePortAccessor &ports) const override {
1162  auto unwrappedIO = this->unwrapIO(s, bb, ports);
1163  this->buildExtendLogic(s, unwrappedIO, /*signExtend=*/signExtend);
1164  };
1165 };
1166 
1167 class ComparisonConversionPattern
1168  : public HandshakeConversionPattern<arith::CmpIOp> {
1169 public:
1170  using HandshakeConversionPattern<arith::CmpIOp>::HandshakeConversionPattern;
1171  void buildModule(arith::CmpIOp op, BackedgeBuilder &bb, RTLBuilder &s,
1172  hw::HWModulePortAccessor &ports) const override {
1173  auto unwrappedIO = this->unwrapIO(s, bb, ports);
1174  auto buildCompareLogic = [&](comb::ICmpPredicate predicate) {
1175  return buildUnitRateJoinLogic(s, unwrappedIO, [&](ValueRange inputs) {
1176  return s.b.create<comb::ICmpOp>(op.getLoc(), predicate, inputs[0],
1177  inputs[1]);
1178  });
1179  };
1180 
1181  switch (op.getPredicate()) {
1182  case arith::CmpIPredicate::eq:
1183  return buildCompareLogic(comb::ICmpPredicate::eq);
1184  case arith::CmpIPredicate::ne:
1185  return buildCompareLogic(comb::ICmpPredicate::ne);
1186  case arith::CmpIPredicate::slt:
1187  return buildCompareLogic(comb::ICmpPredicate::slt);
1188  case arith::CmpIPredicate::ult:
1189  return buildCompareLogic(comb::ICmpPredicate::ult);
1190  case arith::CmpIPredicate::sle:
1191  return buildCompareLogic(comb::ICmpPredicate::sle);
1192  case arith::CmpIPredicate::ule:
1193  return buildCompareLogic(comb::ICmpPredicate::ule);
1194  case arith::CmpIPredicate::sgt:
1195  return buildCompareLogic(comb::ICmpPredicate::sgt);
1196  case arith::CmpIPredicate::ugt:
1197  return buildCompareLogic(comb::ICmpPredicate::ugt);
1198  case arith::CmpIPredicate::sge:
1199  return buildCompareLogic(comb::ICmpPredicate::sge);
1200  case arith::CmpIPredicate::uge:
1201  return buildCompareLogic(comb::ICmpPredicate::uge);
1202  }
1203  assert(false && "invalid CmpIOp");
1204  };
1205 };
1206 
1207 class TruncateConversionPattern
1208  : public HandshakeConversionPattern<arith::TruncIOp> {
1209 public:
1210  using HandshakeConversionPattern<arith::TruncIOp>::HandshakeConversionPattern;
1211  void buildModule(arith::TruncIOp op, BackedgeBuilder &bb, RTLBuilder &s,
1212  hw::HWModulePortAccessor &ports) const override {
1213  auto unwrappedIO = this->unwrapIO(s, bb, ports);
1214  unsigned targetBits =
1215  toValidType(op.getResult().getType()).getIntOrFloatBitWidth();
1216  buildTruncateLogic(s, unwrappedIO, targetBits);
1217  };
1218 };
1219 
1220 class ControlMergeConversionPattern
1221  : public HandshakeConversionPattern<ControlMergeOp> {
1222 public:
1223  using HandshakeConversionPattern<ControlMergeOp>::HandshakeConversionPattern;
1224  void buildModule(ControlMergeOp op, BackedgeBuilder &bb, RTLBuilder &s,
1225  hw::HWModulePortAccessor &ports) const override {
1226  auto unwrappedIO = this->unwrapIO(s, bb, ports);
1227  auto resData = unwrappedIO.outputs[0];
1228  auto resIndex = unwrappedIO.outputs[1];
1229 
1230  // Define some common types and values that will be used.
1231  unsigned numInputs = unwrappedIO.inputs.size();
1232  auto indexType = s.b.getIntegerType(numInputs);
1233  Value noWinner = s.constant(numInputs, 0);
1234  Value c0I1 = s.constant(1, 0);
1235 
1236  // Declare register for storing arbitration winner.
1237  auto won = bb.get(indexType);
1238  Value wonReg = s.reg("won_reg", won, noWinner);
1239 
1240  // Declare wire for arbitration winner.
1241  auto win = bb.get(indexType);
1242 
1243  // Declare wire for whether the circuit just fired and emitted both
1244  // outputs.
1245  auto fired = bb.get(s.b.getI1Type());
1246 
1247  // Declare registers for storing if each output has been emitted.
1248  auto resultEmitted = bb.get(s.b.getI1Type());
1249  Value resultEmittedReg = s.reg("result_emitted_reg", resultEmitted, c0I1);
1250  auto indexEmitted = bb.get(s.b.getI1Type());
1251  Value indexEmittedReg = s.reg("index_emitted_reg", indexEmitted, c0I1);
1252 
1253  // Declare wires for if each output is done.
1254  auto resultDone = bb.get(s.b.getI1Type());
1255  auto indexDone = bb.get(s.b.getI1Type());
1256 
1257  // Create predicates to assert if the win wire or won register hold a
1258  // valid index.
1259  auto hasWinnerCondition = s.rOr({win});
1260  auto hadWinnerCondition = s.rOr({wonReg});
1261 
1262  // Create an arbiter based on a simple priority-encoding scheme to assign
1263  // an index to the win wire. If the won register is set, just use that. In
1264  // the case that won is not set and no input is valid, set a sentinel
1265  // value to indicate no winner was chosen. The constant values are
1266  // remembered in a map so they can be re-used later to assign the arg
1267  // ready outputs.
1268  DenseMap<size_t, Value> argIndexValues;
1269  Value priorityArb = buildPriorityArbiter(s, unwrappedIO.getInputValids(),
1270  noWinner, argIndexValues);
1271  priorityArb = s.mux(hadWinnerCondition, {priorityArb, wonReg});
1272  win.setValue(priorityArb);
1273 
1274  // Create the logic to assign the result and index outputs. The result
1275  // valid output will always be assigned, and if isControl is not set, the
1276  // result data output will also be assigned. The index valid and data
1277  // outputs will always be assigned. The win wire from the arbiter is used
1278  // to index into a tree of muxes to select the chosen input's signal(s),
1279  // and is fed directly to the index output. Both the result and index
1280  // valid outputs are gated on the win wire being set to something other
1281  // than the sentinel value.
1282  auto resultNotEmitted = s.bNot(resultEmittedReg);
1283  auto resultValid = s.bAnd({hasWinnerCondition, resultNotEmitted});
1284  resData.valid->setValue(resultValid);
1285  resData.data->setValue(s.ohMux(win, unwrappedIO.getInputDatas()));
1286 
1287  auto indexNotEmitted = s.bNot(indexEmittedReg);
1288  auto indexValid = s.bAnd({hasWinnerCondition, indexNotEmitted});
1289  resIndex.valid->setValue(indexValid);
1290 
1291  // Use the one-hot win wire to select the index to output in the index
1292  // data.
1293  SmallVector<Value, 8> indexOutputs;
1294  for (size_t i = 0; i < numInputs; ++i)
1295  indexOutputs.push_back(s.constant(64, i));
1296 
1297  auto indexOutput = s.ohMux(win, indexOutputs);
1298  resIndex.data->setValue(indexOutput);
1299 
1300  // Create the logic to set the won register. If the fired wire is
1301  // asserted, we have finished this round and can and reset the register to
1302  // the sentinel value that indicates there is no winner. Otherwise, we
1303  // need to hold the value of the win register until we can fire.
1304  won.setValue(s.mux(fired, {win, noWinner}));
1305 
1306  // Create the logic to set the done wires for the result and index. For
1307  // both outputs, the done wire is asserted when the output is valid and
1308  // ready, or the emitted register for that output is set.
1309  auto resultValidAndReady = s.bAnd({resultValid, resData.ready});
1310  resultDone.setValue(s.bOr({resultValidAndReady, resultEmittedReg}));
1311 
1312  auto indexValidAndReady = s.bAnd({indexValid, resIndex.ready});
1313  indexDone.setValue(s.bOr({indexValidAndReady, indexEmittedReg}));
1314 
1315  // Create the logic to set the fired wire. It is asserted when both result
1316  // and index are done.
1317  fired.setValue(s.bAnd({resultDone, indexDone}));
1318 
1319  // Create the logic to assign the emitted registers. If the fired wire is
1320  // asserted, we have finished this round and can reset the registers to 0.
1321  // Otherwise, we need to hold the values of the done registers until we
1322  // can fire.
1323  resultEmitted.setValue(s.mux(fired, {resultDone, c0I1}));
1324  indexEmitted.setValue(s.mux(fired, {indexDone, c0I1}));
1325 
1326  // Create the logic to assign the arg ready outputs. The logic is
1327  // identical for each arg. If the fired wire is asserted, and the win wire
1328  // holds an arg's index, that arg is ready.
1329  auto winnerOrDefault = s.mux(fired, {noWinner, win});
1330  for (auto [i, ir] : llvm::enumerate(unwrappedIO.getInputReadys())) {
1331  auto &indexValue = argIndexValues[i];
1332  ir->setValue(s.cmp(winnerOrDefault, indexValue, comb::ICmpPredicate::eq));
1333  }
1334  };
1335 };
1336 
1337 class MergeConversionPattern : public HandshakeConversionPattern<MergeOp> {
1338 public:
1339  using HandshakeConversionPattern<MergeOp>::HandshakeConversionPattern;
1340  void buildModule(MergeOp op, BackedgeBuilder &bb, RTLBuilder &s,
1341  hw::HWModulePortAccessor &ports) const override {
1342  auto unwrappedIO = this->unwrapIO(s, bb, ports);
1343  auto resData = unwrappedIO.outputs[0];
1344 
1345  // Define some common types and values that will be used.
1346  unsigned numInputs = unwrappedIO.inputs.size();
1347  auto indexType = s.b.getIntegerType(numInputs);
1348  Value noWinner = s.constant(numInputs, 0);
1349 
1350  // Declare wire for arbitration winner.
1351  auto win = bb.get(indexType);
1352 
1353  // Create predicates to assert if the win wire holds a valid index.
1354  auto hasWinnerCondition = s.rOr(win);
1355 
1356  // Create an arbiter based on a simple priority-encoding scheme to assign an
1357  // index to the win wire. In the case that no input is valid, set a sentinel
1358  // value to indicate no winner was chosen. The constant values are
1359  // remembered in a map so they can be re-used later to assign the arg ready
1360  // outputs.
1361  DenseMap<size_t, Value> argIndexValues;
1362  Value priorityArb = buildPriorityArbiter(s, unwrappedIO.getInputValids(),
1363  noWinner, argIndexValues);
1364  win.setValue(priorityArb);
1365 
1366  // Create the logic to assign the result outputs. The result valid and data
1367  // outputs will always be assigned. The win wire from the arbiter is used to
1368  // index into a tree of muxes to select the chosen input's signal(s). The
1369  // result outputs are gated on the win wire being non-zero.
1370 
1371  resData.valid->setValue(hasWinnerCondition);
1372  resData.data->setValue(s.ohMux(win, unwrappedIO.getInputDatas()));
1373 
1374  // Create the logic to set the done wires for the result. The done wire is
1375  // asserted when the output is valid and ready, or the emitted register is
1376  // set.
1377  auto resultValidAndReady = s.bAnd({hasWinnerCondition, resData.ready});
1378 
1379  // Create the logic to assign the arg ready outputs. The logic is
1380  // identical for each arg. If the fired wire is asserted, and the win wire
1381  // holds an arg's index, that arg is ready.
1382  auto winnerOrDefault = s.mux(resultValidAndReady, {noWinner, win});
1383  for (auto [i, ir] : llvm::enumerate(unwrappedIO.getInputReadys())) {
1384  auto &indexValue = argIndexValues[i];
1385  ir->setValue(s.cmp(winnerOrDefault, indexValue, comb::ICmpPredicate::eq));
1386  }
1387  };
1388 };
1389 
1390 class LoadConversionPattern
1391  : public HandshakeConversionPattern<handshake::LoadOp> {
1392 public:
1393  using HandshakeConversionPattern<
1394  handshake::LoadOp>::HandshakeConversionPattern;
1395  void buildModule(handshake::LoadOp op, BackedgeBuilder &bb, RTLBuilder &s,
1396  hw::HWModulePortAccessor &ports) const override {
1397  auto unwrappedIO = this->unwrapIO(s, bb, ports);
1398  auto addrFromUser = unwrappedIO.inputs[0];
1399  auto dataFromMem = unwrappedIO.inputs[1];
1400  auto controlIn = unwrappedIO.inputs[2];
1401  auto dataToUser = unwrappedIO.outputs[0];
1402  auto addrToMem = unwrappedIO.outputs[1];
1403 
1404  addrToMem.data->setValue(addrFromUser.data);
1405  dataToUser.data->setValue(dataFromMem.data);
1406 
1407  // The valid/ready logic between user address/control to memoryAddr is
1408  // join logic.
1409  buildJoinLogic(s, {addrFromUser, controlIn}, addrToMem);
1410 
1411  // The valid/ready logic between memoryData and outputData is a direct
1412  // connection.
1413  dataToUser.valid->setValue(dataFromMem.valid);
1414  dataFromMem.ready->setValue(dataToUser.ready);
1415  };
1416 };
1417 
1418 class StoreConversionPattern
1419  : public HandshakeConversionPattern<handshake::StoreOp> {
1420 public:
1421  using HandshakeConversionPattern<
1422  handshake::StoreOp>::HandshakeConversionPattern;
1423  void buildModule(handshake::StoreOp op, BackedgeBuilder &bb, RTLBuilder &s,
1424  hw::HWModulePortAccessor &ports) const override {
1425  auto unwrappedIO = this->unwrapIO(s, bb, ports);
1426  auto addrFromUser = unwrappedIO.inputs[0];
1427  auto dataFromUser = unwrappedIO.inputs[1];
1428  auto controlIn = unwrappedIO.inputs[2];
1429  auto dataToMem = unwrappedIO.outputs[0];
1430  auto addrToMem = unwrappedIO.outputs[1];
1431 
1432  // Create a gate that will be asserted when all outputs are ready.
1433  auto outputsReady = s.bAnd({dataToMem.ready, addrToMem.ready});
1434 
1435  // Build the standard join logic from the inputs to the inputsValid and
1436  // outputsReady signals.
1437  HandshakeWire joinWire(bb, s.b.getNoneType());
1438  joinWire.ready->setValue(outputsReady);
1439  OutputHandshake joinOutput = joinWire.getAsOutput();
1440  buildJoinLogic(s, {dataFromUser, addrFromUser, controlIn}, joinOutput);
1441 
1442  // Output address and data signals are connected directly.
1443  addrToMem.data->setValue(addrFromUser.data);
1444  dataToMem.data->setValue(dataFromUser.data);
1445 
1446  // Output valid signals are connected from the inputsValid wire.
1447  addrToMem.valid->setValue(*joinWire.valid);
1448  dataToMem.valid->setValue(*joinWire.valid);
1449  };
1450 };
1451 
1452 class MemoryConversionPattern
1453  : public HandshakeConversionPattern<handshake::MemoryOp> {
1454 public:
1455  using HandshakeConversionPattern<
1456  handshake::MemoryOp>::HandshakeConversionPattern;
1457  void buildModule(handshake::MemoryOp op, BackedgeBuilder &bb, RTLBuilder &s,
1458  hw::HWModulePortAccessor &ports) const override {
1459  auto loc = op.getLoc();
1460 
1461  // Gather up the load and store ports.
1462  auto unwrappedIO = this->unwrapIO(s, bb, ports);
1463  struct LoadPort {
1464  InputHandshake &addr;
1465  OutputHandshake &data;
1466  OutputHandshake &done;
1467  };
1468  struct StorePort {
1469  InputHandshake &addr;
1470  InputHandshake &data;
1471  OutputHandshake &done;
1472  };
1473  SmallVector<LoadPort, 4> loadPorts;
1474  SmallVector<StorePort, 4> storePorts;
1475 
1476  unsigned stCount = op.getStCount();
1477  unsigned ldCount = op.getLdCount();
1478  for (unsigned i = 0, e = ldCount; i != e; ++i) {
1479  LoadPort port = {unwrappedIO.inputs[stCount * 2 + i],
1480  unwrappedIO.outputs[i],
1481  unwrappedIO.outputs[ldCount + stCount + i]};
1482  loadPorts.push_back(port);
1483  }
1484 
1485  for (unsigned i = 0, e = stCount; i != e; ++i) {
1486  StorePort port = {unwrappedIO.inputs[i * 2 + 1],
1487  unwrappedIO.inputs[i * 2],
1488  unwrappedIO.outputs[ldCount + i]};
1489  storePorts.push_back(port);
1490  }
1491 
1492  // used to drive the data wire of the control-only channels.
1493  auto c0I0 = s.constant(0, 0);
1494 
1495  auto cl2dim = llvm::Log2_64_Ceil(op.getMemRefType().getShape()[0]);
1496  auto hlmem = s.b.create<seq::HLMemOp>(
1497  loc, s.clk, s.rst, "_handshake_memory_" + std::to_string(op.getId()),
1498  op.getMemRefType().getShape(), op.getMemRefType().getElementType());
1499 
1500  // Create load ports...
1501  for (auto &ld : loadPorts) {
1502  llvm::SmallVector<Value> addresses = {s.truncate(ld.addr.data, cl2dim)};
1503  auto readData = s.b.create<seq::ReadPortOp>(loc, hlmem.getHandle(),
1504  addresses, ld.addr.valid,
1505  /*latency=*/0);
1506  ld.data.data->setValue(readData);
1507  ld.done.data->setValue(c0I0);
1508  // Create control fork for the load address valid and ready signals.
1509  buildForkLogic(s, bb, ld.addr, {ld.data, ld.done});
1510  }
1511 
1512  // Create store ports...
1513  for (auto &st : storePorts) {
1514  // Create a register to buffer the valid path by 1 cycle, to match the
1515  // write latency of 1.
1516  auto writeValidBufferMuxBE = bb.get(s.b.getI1Type());
1517  auto writeValidBuffer =
1518  s.reg("writeValidBuffer", writeValidBufferMuxBE, s.constant(1, 0));
1519  st.done.valid->setValue(writeValidBuffer);
1520  st.done.data->setValue(c0I0);
1521 
1522  // Create the logic for when both the buffered write valid signal and the
1523  // store complete ready signal are asserted.
1524  auto storeCompleted =
1525  s.bAnd({st.done.ready, writeValidBuffer}, "storeCompleted");
1526 
1527  // Create a signal for when the write valid buffer is empty or the output
1528  // is ready.
1529  auto notWriteValidBuffer = s.bNot(writeValidBuffer);
1530  auto emptyOrComplete =
1531  s.bOr({notWriteValidBuffer, storeCompleted}, "emptyOrComplete");
1532 
1533  // Connect the gate to both the store address ready and store data ready
1534  st.addr.ready->setValue(emptyOrComplete);
1535  st.data.ready->setValue(emptyOrComplete);
1536 
1537  // Create a wire for when both the store address and data are valid.
1538  auto writeValid = s.bAnd({st.addr.valid, st.data.valid}, "writeValid");
1539 
1540  // Create a mux that drives the buffer input. If the emptyOrComplete
1541  // signal is asserted, the mux selects the writeValid signal. Otherwise,
1542  // it selects the buffer output, keeping the output registered until the
1543  // emptyOrComplete signal is asserted.
1544  writeValidBufferMuxBE.setValue(
1545  s.mux(emptyOrComplete, {writeValidBuffer, writeValid}));
1546 
1547  // Instantiate the write port operation - truncate address width to memory
1548  // width.
1549  llvm::SmallVector<Value> addresses = {s.truncate(st.addr.data, cl2dim)};
1550  s.b.create<seq::WritePortOp>(loc, hlmem.getHandle(), addresses,
1551  st.data.data, writeValid,
1552  /*latency=*/1);
1553  }
1554  }
1555 }; // namespace
1556 
1557 class SinkConversionPattern : public HandshakeConversionPattern<SinkOp> {
1558 public:
1559  using HandshakeConversionPattern<SinkOp>::HandshakeConversionPattern;
1560  void buildModule(SinkOp op, BackedgeBuilder &bb, RTLBuilder &s,
1561  hw::HWModulePortAccessor &ports) const override {
1562  auto unwrappedIO = this->unwrapIO(s, bb, ports);
1563  // A sink is always ready to accept a new value.
1564  unwrappedIO.inputs[0].ready->setValue(s.constant(1, 1));
1565  };
1566 };
1567 
1568 class SourceConversionPattern : public HandshakeConversionPattern<SourceOp> {
1569 public:
1570  using HandshakeConversionPattern<SourceOp>::HandshakeConversionPattern;
1571  void buildModule(SourceOp op, BackedgeBuilder &bb, RTLBuilder &s,
1572  hw::HWModulePortAccessor &ports) const override {
1573  auto unwrappedIO = this->unwrapIO(s, bb, ports);
1574  // A source always provides a new (i0-typed) value.
1575  unwrappedIO.outputs[0].valid->setValue(s.constant(1, 1));
1576  unwrappedIO.outputs[0].data->setValue(s.constant(0, 0));
1577  };
1578 };
1579 
1580 class ConstantConversionPattern
1581  : public HandshakeConversionPattern<handshake::ConstantOp> {
1582 public:
1583  using HandshakeConversionPattern<
1584  handshake::ConstantOp>::HandshakeConversionPattern;
1585  void buildModule(handshake::ConstantOp op, BackedgeBuilder &bb, RTLBuilder &s,
1586  hw::HWModulePortAccessor &ports) const override {
1587  auto unwrappedIO = this->unwrapIO(s, bb, ports);
1588  unwrappedIO.outputs[0].valid->setValue(unwrappedIO.inputs[0].valid);
1589  unwrappedIO.inputs[0].ready->setValue(unwrappedIO.outputs[0].ready);
1590  auto constantValue = op->getAttrOfType<IntegerAttr>("value").getValue();
1591  unwrappedIO.outputs[0].data->setValue(s.constant(constantValue));
1592  };
1593 };
1594 
1595 class BufferConversionPattern : public HandshakeConversionPattern<BufferOp> {
1596 public:
1597  using HandshakeConversionPattern<BufferOp>::HandshakeConversionPattern;
1598  void buildModule(BufferOp op, BackedgeBuilder &bb, RTLBuilder &s,
1599  hw::HWModulePortAccessor &ports) const override {
1600  auto unwrappedIO = this->unwrapIO(s, bb, ports);
1601  auto input = unwrappedIO.inputs[0];
1602  auto output = unwrappedIO.outputs[0];
1603  InputHandshake lastStage;
1604  SmallVector<int64_t> initValues;
1605 
1606  // For now, always build seq buffers.
1607  if (op.getInitValues())
1608  initValues = op.getInitValueArray();
1609 
1610  lastStage =
1611  buildSeqBufferLogic(s, bb, toValidType(op.getDataType()),
1612  op.getNumSlots(), input, output, initValues);
1613 
1614  // Connect the last stage to the output handshake.
1615  output.data->setValue(lastStage.data);
1616  output.valid->setValue(lastStage.valid);
1617  lastStage.ready->setValue(output.ready);
1618  };
1619 
1620  struct SeqBufferStage {
1621  SeqBufferStage(Type dataType, InputHandshake &preStage, BackedgeBuilder &bb,
1622  RTLBuilder &s, size_t index,
1623  std::optional<int64_t> initValue)
1624  : dataType(dataType), preStage(preStage), s(s), bb(bb), index(index) {
1625 
1626  // Todo: Change when i0 support is added.
1627  c0s = createZeroDataConst(s, s.loc, dataType);
1628  currentStage.ready = std::make_shared<Backedge>(bb.get(s.b.getI1Type()));
1629 
1630  auto hasInitValue = s.constant(1, initValue.has_value());
1631  auto validBE = bb.get(s.b.getI1Type());
1632  auto validReg = s.reg(getRegName("valid"), validBE, hasInitValue);
1633  auto readyBE = bb.get(s.b.getI1Type());
1634 
1635  Value initValueCs = c0s;
1636  if (initValue.has_value())
1637  initValueCs = s.constant(dataType.getIntOrFloatBitWidth(), *initValue);
1638 
1639  // This could/should be revised but needs a larger rethinking to avoid
1640  // introducing new bugs.
1641  Value dataReg =
1642  buildDataBufferLogic(validReg, initValueCs, validBE, readyBE);
1643  buildControlBufferLogic(validReg, readyBE, dataReg);
1644  }
1645 
1646  StringAttr getRegName(StringRef name) {
1647  return s.b.getStringAttr(name + std::to_string(index) + "_reg");
1648  }
1649 
1650  void buildControlBufferLogic(Value validReg, Backedge &readyBE,
1651  Value dataReg) {
1652  auto c0I1 = s.constant(1, 0);
1653  auto readyRegWire = bb.get(s.b.getI1Type());
1654  auto readyReg = s.reg(getRegName("ready"), readyRegWire, c0I1);
1655 
1656  // Create the logic to drive the current stage valid and potentially
1657  // data.
1658  currentStage.valid = s.mux(readyReg, {validReg, readyReg},
1659  "controlValid" + std::to_string(index));
1660 
1661  // Create the logic to drive the current stage ready.
1662  auto notReadyReg = s.bNot(readyReg);
1663  readyBE.setValue(notReadyReg);
1664 
1665  auto succNotReady = s.bNot(*currentStage.ready);
1666  auto neitherReady = s.bAnd({succNotReady, notReadyReg});
1667  auto ctrlNotReady = s.mux(neitherReady, {readyReg, validReg});
1668  auto bothReady = s.bAnd({*currentStage.ready, readyReg});
1669 
1670  // Create a mux for emptying the register when both are ready.
1671  auto resetSignal = s.mux(bothReady, {ctrlNotReady, c0I1});
1672  readyRegWire.setValue(resetSignal);
1673 
1674  // Add same logic for the data path if necessary.
1675  auto ctrlDataRegBE = bb.get(dataType);
1676  auto ctrlDataReg = s.reg(getRegName("ctrl_data"), ctrlDataRegBE, c0s);
1677  auto dataResult = s.mux(readyReg, {dataReg, ctrlDataReg});
1678  currentStage.data = dataResult;
1679 
1680  auto dataNotReadyMux = s.mux(neitherReady, {ctrlDataReg, dataReg});
1681  auto dataResetSignal = s.mux(bothReady, {dataNotReadyMux, c0s});
1682  ctrlDataRegBE.setValue(dataResetSignal);
1683  }
1684 
1685  Value buildDataBufferLogic(Value validReg, Value initValue,
1686  Backedge &validBE, Backedge &readyBE) {
1687  // Create a signal for when the valid register is empty or the successor
1688  // is ready to accept new token.
1689  auto notValidReg = s.bNot(validReg);
1690  auto emptyOrReady = s.bOr({notValidReg, readyBE});
1691  preStage.ready->setValue(emptyOrReady);
1692 
1693  // Create a mux that drives the register input. If the emptyOrReady
1694  // signal is asserted, the mux selects the predValid signal. Otherwise,
1695  // it selects the register output, keeping the output registered
1696  // unchanged.
1697  auto validRegMux = s.mux(emptyOrReady, {validReg, preStage.valid});
1698 
1699  // Now we can drive the valid register.
1700  validBE.setValue(validRegMux);
1701 
1702  // Create a mux that drives the date register.
1703  auto dataRegBE = bb.get(dataType);
1704  auto dataReg =
1705  s.reg(getRegName("data"),
1706  s.mux(emptyOrReady, {dataRegBE, preStage.data}), initValue);
1707  dataRegBE.setValue(dataReg);
1708  return dataReg;
1709  }
1710 
1711  InputHandshake getOutput() { return currentStage; }
1712 
1713  Type dataType;
1714  InputHandshake &preStage;
1715  InputHandshake currentStage;
1716  RTLBuilder &s;
1717  BackedgeBuilder &bb;
1718  size_t index;
1719 
1720  // A zero-valued constant of equal type as the data type of this buffer.
1721  Value c0s;
1722  };
1723 
1724  InputHandshake buildSeqBufferLogic(RTLBuilder &s, BackedgeBuilder &bb,
1725  Type dataType, unsigned size,
1726  InputHandshake &input,
1727  OutputHandshake &output,
1728  llvm::ArrayRef<int64_t> initValues) const {
1729  // Prime the buffer building logic with an initial stage, which just
1730  // wraps the input handshake.
1731  InputHandshake currentStage = input;
1732 
1733  for (unsigned i = 0; i < size; ++i) {
1734  bool isInitialized = i < initValues.size();
1735  auto initValue =
1736  isInitialized ? std::optional<int64_t>(initValues[i]) : std::nullopt;
1737  currentStage = SeqBufferStage(dataType, currentStage, bb, s, i, initValue)
1738  .getOutput();
1739  }
1740 
1741  return currentStage;
1742  };
1743 };
1744 
1745 class IndexCastConversionPattern
1746  : public HandshakeConversionPattern<arith::IndexCastOp> {
1747 public:
1748  using HandshakeConversionPattern<
1749  arith::IndexCastOp>::HandshakeConversionPattern;
1750  void buildModule(arith::IndexCastOp op, BackedgeBuilder &bb, RTLBuilder &s,
1751  hw::HWModulePortAccessor &ports) const override {
1752  auto unwrappedIO = this->unwrapIO(s, bb, ports);
1753  unsigned sourceBits =
1754  toValidType(op.getIn().getType()).getIntOrFloatBitWidth();
1755  unsigned targetBits =
1756  toValidType(op.getResult().getType()).getIntOrFloatBitWidth();
1757  if (targetBits < sourceBits)
1758  buildTruncateLogic(s, unwrappedIO, targetBits);
1759  else
1760  buildExtendLogic(s, unwrappedIO, /*signExtend=*/true);
1761  };
1762 };
1763 
1764 template <typename T>
1765 class ExtModuleConversionPattern : public OpConversionPattern<T> {
1766 public:
1767  ExtModuleConversionPattern(ESITypeConverter &typeConverter,
1768  MLIRContext *context, OpBuilder &submoduleBuilder,
1769  HandshakeLoweringState &ls)
1770  : OpConversionPattern<T>::OpConversionPattern(typeConverter, context),
1771  submoduleBuilder(submoduleBuilder), ls(ls) {}
1772  using OpAdaptor = typename T::Adaptor;
1773 
1774  LogicalResult
1775  matchAndRewrite(T op, OpAdaptor adaptor,
1776  ConversionPatternRewriter &rewriter) const override {
1777 
1778  hw::HWModuleLike implModule = checkSubModuleOp(ls.parentModule, op);
1779  if (!implModule) {
1780  auto portInfo = ModulePortInfo(getPortInfoForOp(op));
1781  implModule = submoduleBuilder.create<hw::HWModuleExternOp>(
1782  op.getLoc(), submoduleBuilder.getStringAttr(getSubModuleName(op)),
1783  portInfo);
1784  }
1785 
1786  llvm::SmallVector<Value> operands = adaptor.getOperands();
1787  addSequentialIOOperandsIfNeeded(op, operands);
1788  rewriter.replaceOpWithNewOp<hw::InstanceOp>(
1789  op, implModule, rewriter.getStringAttr(ls.nameUniquer(op)), operands);
1790  return success();
1791  }
1792 
1793 private:
1794  OpBuilder &submoduleBuilder;
1795  HandshakeLoweringState &ls;
1796 };
1797 
1798 class FuncOpConversionPattern : public OpConversionPattern<handshake::FuncOp> {
1799 public:
1800  using OpConversionPattern::OpConversionPattern;
1801 
1802  LogicalResult
1803  matchAndRewrite(handshake::FuncOp op, OpAdaptor operands,
1804  ConversionPatternRewriter &rewriter) const override {
1805  ModulePortInfo ports =
1806  getPortInfoForOpTypes(op, op.getArgumentTypes(), op.getResultTypes());
1807 
1808  HWModuleLike hwModule;
1809  if (op.isExternal()) {
1810  hwModule = rewriter.create<hw::HWModuleExternOp>(
1811  op.getLoc(), rewriter.getStringAttr(op.getName()), ports);
1812  } else {
1813  auto hwModuleOp = rewriter.create<hw::HWModuleOp>(
1814  op.getLoc(), rewriter.getStringAttr(op.getName()), ports);
1815  auto args = hwModuleOp.getBodyBlock()->getArguments().drop_back(2);
1816  rewriter.inlineBlockBefore(&op.getBody().front(),
1817  hwModuleOp.getBodyBlock()->getTerminator(),
1818  args);
1819  hwModule = hwModuleOp;
1820  }
1821 
1822  // Was any predeclaration associated with this func? If so, replace uses
1823  // with the newly created module and erase the predeclaration.
1824  if (auto predecl =
1825  op->getAttrOfType<FlatSymbolRefAttr>(kPredeclarationAttr)) {
1826  auto *parentOp = op->getParentOp();
1827  auto *predeclModule =
1828  SymbolTable::lookupSymbolIn(parentOp, predecl.getValue());
1829  if (predeclModule) {
1830  if (failed(SymbolTable::replaceAllSymbolUses(
1831  predeclModule, hwModule.getModuleNameAttr(), parentOp)))
1832  return failure();
1833  rewriter.eraseOp(predeclModule);
1834  }
1835  }
1836 
1837  rewriter.eraseOp(op);
1838  return success();
1839  }
1840 };
1841 
1842 } // namespace
1843 
1844 //===----------------------------------------------------------------------===//
1845 // HW Top-module Related Functions
1846 //===----------------------------------------------------------------------===//
1847 
1848 static LogicalResult convertFuncOp(ESITypeConverter &typeConverter,
1849  ConversionTarget &target,
1850  handshake::FuncOp op,
1851  OpBuilder &moduleBuilder) {
1852 
1853  std::map<std::string, unsigned> instanceNameCntr;
1854  NameUniquer instanceUniquer = [&](Operation *op) {
1855  std::string instName = getCallName(op);
1856  if (auto idAttr = op->getAttrOfType<IntegerAttr>("handshake_id"); idAttr) {
1857  // We use a special naming convention for operations which have a
1858  // 'handshake_id' attribute.
1859  instName += "_id" + std::to_string(idAttr.getValue().getZExtValue());
1860  } else {
1861  // Fallback to just prefixing with an integer.
1862  instName += std::to_string(instanceNameCntr[instName]++);
1863  }
1864  return instName;
1865  };
1866 
1867  auto ls = HandshakeLoweringState{op->getParentOfType<mlir::ModuleOp>(),
1868  instanceUniquer};
1869  RewritePatternSet patterns(op.getContext());
1870  patterns.insert<FuncOpConversionPattern, ReturnConversionPattern>(
1871  op.getContext());
1872  patterns.insert<JoinConversionPattern, ForkConversionPattern,
1873  SyncConversionPattern>(typeConverter, op.getContext(),
1874  moduleBuilder, ls);
1875 
1876  patterns.insert<
1877  // Comb operations.
1878  UnitRateConversionPattern<arith::AddIOp, comb::AddOp>,
1879  UnitRateConversionPattern<arith::SubIOp, comb::SubOp>,
1880  UnitRateConversionPattern<arith::MulIOp, comb::MulOp>,
1881  UnitRateConversionPattern<arith::DivUIOp, comb::DivSOp>,
1882  UnitRateConversionPattern<arith::DivSIOp, comb::DivUOp>,
1883  UnitRateConversionPattern<arith::RemUIOp, comb::ModUOp>,
1884  UnitRateConversionPattern<arith::RemSIOp, comb::ModSOp>,
1885  UnitRateConversionPattern<arith::AndIOp, comb::AndOp>,
1886  UnitRateConversionPattern<arith::OrIOp, comb::OrOp>,
1887  UnitRateConversionPattern<arith::XOrIOp, comb::XorOp>,
1888  UnitRateConversionPattern<arith::ShLIOp, comb::ShlOp>,
1889  UnitRateConversionPattern<arith::ShRUIOp, comb::ShrUOp>,
1890  UnitRateConversionPattern<arith::ShRSIOp, comb::ShrSOp>,
1891  UnitRateConversionPattern<arith::SelectOp, comb::MuxOp>,
1892  // HW operations.
1893  StructCreateConversionPattern,
1894  // Handshake operations.
1895  ConditionalBranchConversionPattern, MuxConversionPattern,
1896  PackConversionPattern, UnpackConversionPattern,
1897  ComparisonConversionPattern, BufferConversionPattern,
1898  SourceConversionPattern, SinkConversionPattern, ConstantConversionPattern,
1899  MergeConversionPattern, ControlMergeConversionPattern,
1900  LoadConversionPattern, StoreConversionPattern, MemoryConversionPattern,
1901  InstanceConversionPattern,
1902  // Arith operations.
1903  ExtendConversionPattern<arith::ExtUIOp, /*signExtend=*/false>,
1904  ExtendConversionPattern<arith::ExtSIOp, /*signExtend=*/true>,
1905  TruncateConversionPattern, IndexCastConversionPattern>(
1906  typeConverter, op.getContext(), moduleBuilder, ls);
1907 
1908  if (failed(applyPartialConversion(op, target, std::move(patterns))))
1909  return op->emitOpError() << "error during conversion";
1910  return success();
1911 }
1912 
1913 namespace {
1914 class HandshakeToHWPass : public HandshakeToHWBase<HandshakeToHWPass> {
1915 public:
1916  void runOnOperation() override {
1917  mlir::ModuleOp mod = getOperation();
1918 
1919  // Lowering to HW requires that every value is used exactly once. Check
1920  // whether this precondition is met, and if not, exit.
1921  for (auto f : mod.getOps<handshake::FuncOp>()) {
1922  if (failed(verifyAllValuesHasOneUse(f))) {
1923  f.emitOpError() << "HandshakeToHW: failed to verify that all values "
1924  "are used exactly once. Remember to run the "
1925  "fork/sink materialization pass before HW lowering.";
1926  signalPassFailure();
1927  return;
1928  }
1929  }
1930 
1931  // Resolve the instance graph to get a top-level module.
1932  std::string topLevel;
1934  SmallVector<std::string> sortedFuncs;
1935  if (resolveInstanceGraph(mod, uses, topLevel, sortedFuncs).failed()) {
1936  signalPassFailure();
1937  return;
1938  }
1939 
1940  ESITypeConverter typeConverter;
1941  ConversionTarget target(getContext());
1942  // All top-level logic of a handshake module will be the interconnectivity
1943  // between instantiated modules.
1944  target.addLegalOp<hw::HWModuleOp, hw::HWModuleExternOp, hw::OutputOp,
1945  hw::InstanceOp>();
1946  target
1947  .addIllegalDialect<handshake::HandshakeDialect, arith::ArithDialect>();
1948 
1949  // Convert the handshake.func operations in post-order wrt. the instance
1950  // graph. This ensures that any referenced submodules (through
1951  // handshake.instance) has already been lowered, and their HW module
1952  // equivalents are available.
1953  OpBuilder submoduleBuilder(mod.getContext());
1954  submoduleBuilder.setInsertionPointToStart(mod.getBody());
1955  for (auto &funcName : llvm::reverse(sortedFuncs)) {
1956  auto funcOp = mod.lookupSymbol<handshake::FuncOp>(funcName);
1957  assert(funcOp && "handshake.func not found in module!");
1958  if (failed(
1959  convertFuncOp(typeConverter, target, funcOp, submoduleBuilder))) {
1960  signalPassFailure();
1961  return;
1962  }
1963  }
1964 
1965  // Second stage: Convert any handshake.extmemory operations and the
1966  // top-level I/O associated with these.
1967  for (auto hwModule : mod.getOps<hw::HWModuleOp>())
1968  if (failed(convertExtMemoryOps(hwModule)))
1969  return signalPassFailure();
1970  }
1971 };
1972 } // end anonymous namespace
1973 
1974 std::unique_ptr<mlir::Pass> circt::createHandshakeToHWPass() {
1975  return std::make_unique<HandshakeToHWPass>();
1976 }
assert(baseType &&"element must be base type")
return wrap(CMemoryType::get(unwrap(ctx), baseType, numElements))
MlirType elementType
Definition: CHIRRTL.cpp:29
static std::string valueName(Operation *scopeOp, Value v)
Convenience function for getting the SSA name of v under the scope of operation scopeOp.
Definition: CalyxOps.cpp:120
static SmallVector< T > concat(const SmallVectorImpl< T > &a, const SmallVectorImpl< T > &b)
Returns a new vector containing the concatenation of vectors a and b.
Definition: CalyxOps.cpp:539
static Type tupleToStruct(TupleType tuple)
Definition: DCToHW.cpp:43
std::function< std::string(Operation *)> NameUniquer
Definition: DCToHW.cpp:40
static void buildModule(OpBuilder &builder, OperationState &result, StringAttr name, ArrayRef< PortInfo > ports, ArrayAttr annotations, ArrayAttr layers)
Definition: FIRRTLOps.cpp:978
int32_t width
Definition: FIRRTL.cpp:36
@ Input
Definition: HW.h:35
@ Output
Definition: HW.h:35
static std::string getCallName(Operation *op)
static SmallVector< Type > filterNoneTypes(ArrayRef< Type > input)
Filters NoneType's from the input.
static Type getOperandDataType(Value op)
Extracts the type of the data-carrying type of opType.
static DiscriminatingTypes getHandshakeDiscriminatingTypes(Operation *op)
static ModulePortInfo getPortInfoForOp(Operation *op)
Returns a vector of PortInfo's which defines the HW interface of the to-be-converted op.
static std::string getBareSubModuleName(Operation *oldOp)
Returns a submodule name resulting from an operation, without discriminating type information.
static std::string getSubModuleName(Operation *oldOp)
Construct a name for creating HW sub-module.
static HWModuleLike checkSubModuleOp(mlir::ModuleOp parentModule, StringRef modName)
Check whether a submodule with the same name has been created elsewhere in the top level module.
std::pair< SmallVector< Type >, SmallVector< Type > > DiscriminatingTypes
Returns a set of types which may uniquely identify the provided op.
static LogicalResult convertFuncOp(ESITypeConverter &typeConverter, ConversionTarget &target, handshake::FuncOp op, OpBuilder &moduleBuilder)
static llvm::SmallVector< hw::detail::FieldInfo > portToFieldInfo(llvm::ArrayRef< hw::PortInfo > portInfo)
static std::string getTypeName(Location loc, Type type)
Get type name.
static LogicalResult convertExtMemoryOps(HWModuleOp mod)
static EvaluatorValuePtr unwrap(OMEvaluatorValue c)
Definition: OM.cpp:96
llvm::SmallVector< StringAttr > inputs
llvm::SmallVector< StringAttr > outputs
Builder builder
Instantiate one of these and use it to build typed backedges.
Backedge get(mlir::Type resultType, mlir::LocationAttr optionalLoc={})
Create a typed backedge.
Backedge is a wrapper class around a Value.
void setValue(mlir::Value)
Channels are the basic communication primitives.
Definition: Types.h:63
const Type * getInner() const
Definition: Types.h:66
def create(cls, result_type, reset=None, reset_value=None, name=None, sym_name=None, **kwargs)
Definition: seq.py:137
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
Definition: CalyxOps.cpp:54
Value createOrFoldSExt(Location loc, Value value, Type destTy, OpBuilder &builder)
Create a sign extension operation from a value of integer type to an equal or larger integer type.
Definition: CombOps.cpp:25
mlir::Type innerType(mlir::Type type)
Definition: ESITypes.cpp:184
hw::ModulePortInfo getPortInfoForOpTypes(mlir::Operation *op, TypeRange inputs, TypeRange outputs)
std::map< std::string, std::set< std::string > > InstanceGraph
Iterates over the handshake::FuncOp's in the program to build an instance graph.
LogicalResult resolveInstanceGraph(ModuleOp moduleOp, InstanceGraph &instanceGraph, std::string &topLevel, SmallVectorImpl< std::string > &sortedFuncs)
Iterates over the handshake::FuncOp's in the program to build an instance graph.
Definition: PassHelpers.cpp:38
static constexpr const char * kPredeclarationAttr
Definition: HandshakeToHW.h:37
LogicalResult verifyAllValuesHasOneUse(handshake::FuncOp op)
Type toValidType(Type t)
esi::ChannelType esiWrapper(mlir::Type t)
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Definition: DebugAnalysis.h:21
std::unique_ptr< mlir::Pass > createHandshakeToHWPass()
def reg(value, clock, reset=None, reset_value=None, name=None, sym_name=None)
Definition: seq.py:20
This holds a decoded list of input/inout and output ports for a module or instance.
PortDirectionRange getInputs()
PortDirectionRange getOutputs()