11 #include "mlir/Pass/Pass.h"
12 #include "mlir/Transforms/DialectConversion.h"
13 #include "llvm/ADT/TypeSwitch.h"
17 #define GEN_PASS_DEF_FLATTENIO
18 #include "circt/Dialect/HW/Passes.h.inc"
23 using namespace circt;
35 return llvm::none_of(moduleLikeOp.getHWModuleType().getPortTypes(),
40 llvm::SmallVector<Type> inner;
41 t.getInnerTypes(inner);
42 for (
auto [index,
innerType] : llvm::enumerate(inner))
50 static SmallVector<Value>
flattenValues(ArrayRef<ValueRange> values) {
51 SmallVector<Value> result;
52 for (
const auto &vals : values)
53 llvm::append_range(result, vals);
59 OutputOpConversion(TypeConverter &typeConverter, MLIRContext *context,
60 DenseSet<Operation *> *opVisited)
64 matchAndRewrite(hw::OutputOp op, OpAdaptor adaptor,
65 ConversionPatternRewriter &rewriter)
const override {
66 llvm::SmallVector<Value> convOperands;
69 for (
auto operand : adaptor.getOperands()) {
71 auto explodedStruct = rewriter.create<hw::StructExplodeOp>(
73 llvm::copy(explodedStruct.getResults(),
74 std::back_inserter(convOperands));
76 convOperands.push_back(operand);
81 opVisited->insert(op->getParentOp());
82 rewriter.replaceOpWithNewOp<hw::OutputOp>(op, convOperands);
87 matchAndRewrite(hw::OutputOp op, OneToNOpAdaptor adaptor,
88 ConversionPatternRewriter &rewriter)
const override {
89 llvm::SmallVector<Value> convOperands;
94 auto explodedStruct = rewriter.create<hw::StructExplodeOp>(
96 llvm::copy(explodedStruct.getResults(),
97 std::back_inserter(convOperands));
99 convOperands.push_back(operand);
104 opVisited->insert(op->getParentOp());
105 rewriter.replaceOpWithNewOp<hw::OutputOp>(op, convOperands);
108 DenseSet<Operation *> *opVisited;
112 InstanceOpConversion(TypeConverter &typeConverter, MLIRContext *context,
113 DenseSet<hw::InstanceOp> *convertedOps,
114 const StringSet<> *externModules)
116 externModules(externModules) {}
119 matchAndRewrite(hw::InstanceOp op, OneToNOpAdaptor adaptor,
120 ConversionPatternRewriter &rewriter)
const override {
121 auto referencedMod = op.getReferencedModuleNameAttr();
124 if (externModules->contains(referencedMod.getValue()))
127 auto loc = op.getLoc();
129 llvm::SmallVector<Value> convOperands;
132 auto explodedStruct = rewriter.create<hw::StructExplodeOp>(
134 llvm::copy(explodedStruct.getResults(),
135 std::back_inserter(convOperands));
137 convOperands.push_back(operand);
142 llvm::SmallVector<Type> newResultTypes;
143 for (
auto oldResultType : op.getResultTypes()) {
145 for (
auto t : structType.getElements())
146 newResultTypes.push_back(t.type);
148 newResultTypes.push_back(oldResultType);
153 auto newInstance = rewriter.create<hw::InstanceOp>(
154 loc, newResultTypes, op.getInstanceNameAttr(),
156 op.getArgNamesAttr(), op.getResultNamesAttr(), op.getParametersAttr(),
157 op.getInnerSymAttr(), op.getDoNotPrintAttr());
160 llvm::SmallVector<Value> convResults;
161 size_t oldResultCntr = 0;
162 for (
size_t resIndex = 0; resIndex < newInstance.getNumResults();
164 Type oldResultType = op.getResultTypes()[oldResultCntr];
166 size_t nElements = structType.getElements().size();
169 newInstance.getResults().slice(resIndex, nElements));
170 convResults.push_back(implodedStruct.getResult());
171 resIndex += nElements - 1;
173 convResults.push_back(newInstance.getResult(resIndex));
177 rewriter.replaceOp(op, convResults);
178 convertedOps->insert(newInstance);
182 DenseSet<hw::InstanceOp> *convertedOps;
183 const StringSet<> *externModules;
186 using IOTypes = std::pair<TypeRange, TypeRange>;
190 DenseMap<unsigned, hw::StructType> argStructs, resStructs;
193 SmallVector<Type> argTypes, resTypes;
196 class FlattenIOTypeConverter :
public TypeConverter {
198 FlattenIOTypeConverter() {
199 addConversion([](Type type, SmallVectorImpl<Type> &results) {
202 results.push_back(type);
204 for (
auto field : structType.getElements())
205 results.push_back(field.type);
212 addTargetMaterialization([](OpBuilder &builder, TypeRange resultTypes,
213 ValueRange inputs, Location loc) {
214 if (inputs.size() != 1 && !
isStructType(inputs[0].getType()))
217 auto explodeOp = builder.create<hw::StructExplodeOp>(loc, inputs[0]);
218 return ValueRange(explodeOp.getResults());
220 addTargetMaterialization([](OpBuilder &builder, hw::StructType type,
221 ValueRange inputs, Location loc) {
223 return result.getResult();
226 addTargetMaterialization([](OpBuilder &builder, hw::TypeAliasType type,
227 ValueRange inputs, Location loc) {
229 return result.getResult();
236 template <
typename... TOp>
238 ConversionTarget &target,
240 FlattenIOTypeConverter &typeConverter) {
255 target.addDynamicallyLegalOp<TOp...>([&](hw::HWModuleLike moduleLikeOp) {
260 auto ioInfoIt = ioMap.find(moduleLikeOp);
261 if (ioInfoIt == ioMap.end()) {
266 auto ioInfo = ioInfoIt->second;
268 auto compareTypes = [&](TypeRange oldTypes, TypeRange newTypes) {
269 return llvm::any_of(llvm::zip(oldTypes, newTypes), [&](
auto typePair) {
270 auto oldType = std::get<0>(typePair);
271 auto newType = std::get<1>(typePair);
272 return oldType != newType;
275 auto mtype = moduleLikeOp.getHWModuleType();
276 if (
compareTypes(mtype.getOutputTypes(), ioInfo.resTypes) ||
286 template <
typename T>
288 return llvm::any_of(module.getBody()->getOps<T>(),
289 [](T op) { return !isLegalModLikeOp(op); });
292 template <
typename T>
293 static DenseMap<Operation *, IOTypes>
populateIOMap(mlir::ModuleOp module) {
294 DenseMap<Operation *, IOTypes> ioMap;
295 for (
auto op : module.getOps<T>())
296 ioMap[op] = {op.getArgumentTypes(), op.getResultTypes()};
300 template <
typename ModTy,
typename T>
301 static llvm::SmallVector<Attribute>
303 DenseMap<unsigned, hw::StructType> &structMap, T oldNames,
305 llvm::SmallVector<Attribute> newNames;
306 for (
auto [i, oldName] : llvm::enumerate(oldNames)) {
308 auto it = structMap.find(i);
309 if (it == structMap.end()) {
317 auto structType = it->second;
318 for (
auto field : structType.getElements())
320 op->getContext(), oldName + Twine(joinChar) + field.name.str()));
325 template <
typename ModTy>
330 SmallVector<Attribute> newNames;
331 SmallVector<hw::ModulePort> oldPorts(oldModType.getPorts().begin(),
332 oldModType.getPorts().end());
333 for (
auto oldPort : oldPorts) {
334 auto oldName = oldPort.name;
336 for (
auto field : structType.getElements()) {
339 oldName.getValue() + Twine(joinChar) + field.name.str()));
342 newNames.push_back(oldName);
344 op.setAllPortNames(newNames);
347 static llvm::SmallVector<Location>
349 SmallVectorImpl<Location> &oldLocs) {
350 llvm::SmallVector<Location> newLocs;
351 for (
auto [i, oldLoc] : llvm::enumerate(oldLocs)) {
353 auto it = structMap.find(i);
354 if (it == structMap.end()) {
356 newLocs.push_back(oldLoc);
360 auto structType = it->second;
361 for (
size_t i = 0, e = structType.getElements().size(); i < e; ++i)
362 newLocs.push_back(oldLoc);
372 DenseMap<unsigned, hw::StructType> &structMap) {
373 auto locs = op.getInputLocs();
374 if (locs.empty() || op.getModuleBody().empty())
376 for (
auto [arg, loc] : llvm::zip(op.getBodyBlock()->getArguments(), locs))
380 static void setIOInfo(hw::HWModuleLike op, IOInfo &ioInfo) {
381 ioInfo.argTypes = op.getInputTypes();
382 ioInfo.resTypes = op.getOutputTypes();
383 for (
auto [i, arg] : llvm::enumerate(ioInfo.argTypes)) {
385 ioInfo.argStructs[i] = structType;
387 for (
auto [i, res] : llvm::enumerate(ioInfo.resTypes)) {
389 ioInfo.resStructs[i] = structType;
393 template <
typename T>
395 DenseMap<Operation *, IOInfo> ioInfoMap;
396 for (
auto op : module.getOps<T>()) {
399 ioInfoMap[op] = ioInfo;
404 template <
typename T>
406 StringSet<> &externModules,
408 auto *ctx = module.getContext();
409 FlattenIOTypeConverter typeConverter;
414 while (hasUnconvertedOps<T>(module)) {
415 ConversionTarget target(*ctx);
417 target.addLegalDialect<hw::HWDialect>();
421 auto ioInfoMap = populateIOInfoMap<T>(module);
426 llvm::DenseSet<hw::InstanceOp> convertedInstances;
431 DenseSet<Operation *> opVisited;
432 patterns.add<OutputOpConversion>(typeConverter, ctx, &opVisited);
434 patterns.add<InstanceOpConversion>(typeConverter, ctx, &convertedInstances,
436 target.addDynamicallyLegalOp<hw::OutputOp>(
437 [&](
auto op) {
return opVisited.contains(op->getParentOp()); });
438 target.addDynamicallyLegalOp<hw::InstanceOp>([&](hw::InstanceOp op) {
439 auto refName = op.getReferencedModuleName();
440 return externModules.contains(refName) ||
441 (llvm::none_of(op->getOperands(),
443 return isStructType(operand.getType());
445 llvm::none_of(op->getResultTypes(),
446 [](
auto result) { return isStructType(result); }));
449 DenseMap<Operation *, ArrayAttr> oldArgNames, oldResNames;
450 DenseMap<Operation *, SmallVector<Location>> oldArgLocs, oldResLocs;
451 DenseMap<Operation *, hw::ModuleType> oldModTypes;
453 for (
auto op : module.getOps<T>()) {
454 oldModTypes[op] = op.getHWModuleType();
455 oldArgNames[op] =
ArrayAttr::get(module.getContext(), op.getInputNames());
458 oldArgLocs[op] = op.getInputLocs();
459 oldResLocs[op] = op.getOutputLocs();
463 addSignatureConversion<T>(ioInfoMap, target,
patterns, typeConverter);
465 if (failed(applyPartialConversion(module, target, std::move(
patterns))))
469 for (
auto op : module.getOps<T>()) {
470 auto ioInfo = ioInfoMap[op];
474 newArgLocs.append(newResLocs.begin(), newResLocs.end());
475 op.setAllPortLocs(newArgLocs);
480 for (
auto instanceOp : convertedInstances) {
482 cast<hw::HWModuleLike>(SymbolTable::lookupNearestSymbolFrom(
483 instanceOp, instanceOp.getReferencedModuleNameAttr()));
486 if (!ioInfoMap.contains(targetModule)) {
489 ioInfoMap[targetModule] = ioInfo;
490 oldArgNames[targetModule] =
491 ArrayAttr::get(module.getContext(), targetModule.getInputNames());
492 oldResNames[targetModule] =
493 ArrayAttr::get(module.getContext(), targetModule.getOutputNames());
494 oldArgLocs[targetModule] = targetModule.getInputLocs();
495 oldResLocs[targetModule] = targetModule.getOutputLocs();
497 ioInfo = ioInfoMap[targetModule];
500 instanceOp.getContext(),
502 instanceOp,
"argNames", ioInfo.argStructs,
503 oldArgNames[targetModule].template getAsValueRange<StringAttr>(),
506 instanceOp.getContext(),
508 instanceOp,
"resultNames", ioInfo.resStructs,
509 oldResNames[targetModule].template getAsValueRange<StringAttr>(),
524 template <
typename... TOps>
526 StringSet<> &externModules,
char joinChar) {
527 return (failed(flattenOpsOfType<TOps>(module, recursive, externModules,
534 class FlattenIOPass :
public circt::hw::impl::FlattenIOBase<FlattenIOPass> {
536 FlattenIOPass(
bool recursiveFlag,
bool flattenExternFlag,
char join) {
537 recursive = recursiveFlag;
538 flattenExtern = flattenExternFlag;
542 void runOnOperation()
override {
543 ModuleOp module = getOperation();
544 if (!flattenExtern) {
547 externModules.insert(m.getModuleName());
548 if (flattenIO<hw::HWModuleOp, hw::HWModuleGeneratedOp>(
549 module, recursive, externModules, joinChar))
555 hw::HWModuleGeneratedOp>(module, recursive, externModules,
561 StringSet<> externModules;
570 bool flattenExternFlag,
572 return std::make_unique<FlattenIOPass>(recursiveFlag, flattenExternFlag,
static LogicalResult compareTypes(Location loc, TypeRange rangeA, TypeRange rangeB)
static llvm::SmallVector< Type > getInnerTypes(hw::StructType t)
static llvm::SmallVector< Location > updateLocAttribute(DenseMap< unsigned, hw::StructType > &structMap, SmallVectorImpl< Location > &oldLocs)
static bool isLegalModLikeOp(hw::HWModuleLike moduleLikeOp)
static void updateBlockLocations(hw::HWModuleLike op, DenseMap< unsigned, hw::StructType > &structMap)
The conversion framework seems to throw away block argument locations.
static bool hasUnconvertedOps(mlir::ModuleOp module)
static llvm::SmallVector< Attribute > updateNameAttribute(ModTy op, StringRef attrName, DenseMap< unsigned, hw::StructType > &structMap, T oldNames, char joinChar)
static void setIOInfo(hw::HWModuleLike op, IOInfo &ioInfo)
static LogicalResult flattenOpsOfType(ModuleOp module, bool recursive, StringSet<> &externModules, char joinChar)
static DenseMap< Operation *, IOTypes > populateIOMap(mlir::ModuleOp module)
static void addSignatureConversion(DenseMap< Operation *, IOInfo > &ioMap, ConversionTarget &target, RewritePatternSet &patterns, FlattenIOTypeConverter &typeConverter)
static bool isStructType(Type type)
static void updateModulePortNames(ModTy op, hw::ModuleType oldModType, char joinChar)
static hw::StructType getStructType(Type type)
static bool flattenIO(ModuleOp module, bool recursive, StringSet<> &externModules, char joinChar)
static DenseMap< Operation *, IOInfo > populateIOInfoMap(mlir::ModuleOp module)
static SmallVector< Value > flattenValues(ArrayRef< ValueRange > values)
Flatten the given value ranges into a single vector of values.
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
mlir::Type innerType(mlir::Type type)
void populateHWModuleLikeTypeConversionPattern(StringRef moduleLikeOpName, RewritePatternSet &patterns, TypeConverter &converter)
mlir::Type getCanonicalType(mlir::Type type)
std::unique_ptr< mlir::Pass > createFlattenIOPass(bool recursiveFlag=true, bool flattenExternFlag=false, char joinChar='.')
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.