CIRCT 24.0.0git
Loading...
Searching...
No Matches
FreezePaths.cpp
Go to the documentation of this file.
1//===- FreezePaths.cpp - Freeze Paths pass ----------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Contains the definitions of the OM freeze paths pass.
10//
11//===----------------------------------------------------------------------===//
12
19#include "mlir/Pass/Pass.h"
20
21namespace circt {
22namespace om {
23#define GEN_PASS_DEF_FREEZEPATHS
24#include "circt/Dialect/OM/OMPasses.h.inc"
25} // namespace om
26} // namespace circt
27
28using namespace circt;
29using namespace om;
30
31namespace {
32struct PathVisitor {
33 PathVisitor(hw::InstanceGraph &instanceGraph, hw::InnerRefNamespace &irn,
34 std::function<StringAttr(Operation *)> &getOpName)
35 : instanceGraph(instanceGraph), irn(irn), getOpNameFallback(getOpName) {}
36
37 StringAttr field;
38 LogicalResult processPath(Location loc, hw::HierPathOp hierPathOp,
39 PathAttr &targetPath, StringAttr &bottomModule,
40 StringAttr &component, StringAttr &field);
41 LogicalResult process(BasePathCreateOp pathOp);
42 LogicalResult process(PathCreateOp pathOp);
43 LogicalResult process(EmptyPathOp pathOp);
44 LogicalResult run(ModuleOp module);
45 hw::InstanceGraph &instanceGraph;
46 hw::InnerRefNamespace &irn;
47 std::function<StringAttr(Operation *)> getOpNameFallback;
48};
49} // namespace
50
51static LogicalResult getAccessPath(Location loc, Type type, size_t fieldId,
52 StringAttr &result) {
53 SmallString<64> field;
54 while (fieldId) {
55 if (auto aliasType = dyn_cast<hw::TypeAliasType>(type))
56 type = aliasType.getCanonicalType();
57 if (auto structType = dyn_cast<hw::StructType>(type)) {
58 auto index = structType.getIndexForFieldID(fieldId);
59 auto &element = structType.getElements()[index];
60 field.push_back('.');
61 llvm::append_range(field, element.name.getValue());
62 type = element.type;
63 fieldId -= structType.getFieldID(index);
64 } else if (auto arrayType = dyn_cast<hw::ArrayType>(type)) {
65 auto index = arrayType.getIndexForFieldID(fieldId);
66 field.push_back('[');
67 Twine(index).toVector(field);
68 field.push_back(']');
69 type = arrayType.getElementType();
70 fieldId -= arrayType.getFieldID(index);
71 } else {
72 return emitError(loc) << "can't create access path with fieldID "
73 << fieldId << " in type " << type;
74 }
75 }
76 result = StringAttr::get(loc->getContext(), field);
77 return success();
78}
79
80// Check if the element type of a potentially nested list includes path types.
81static bool hasPathType(Type type) {
82 bool isPathType = false;
83 type.walk([&](Type innerType) {
84 if (isa<BasePathType, PathType>(innerType))
85 isPathType = true;
86 });
87
88 return isPathType;
89}
90
91mlir::AttrTypeReplacer makeReplacer() {
92 mlir::AttrTypeReplacer replacer;
93 replacer.addReplacement([](BasePathType innerType) {
94 return FrozenBasePathType::get(innerType.getContext());
95 });
96 replacer.addReplacement([](PathType innerType) {
97 return FrozenPathType::get(innerType.getContext());
98 });
99 return replacer;
100}
101
102// Convert potentially nested lists of PathType or BasePathType to frozen lists.
103static Type processType(Type type) {
104 mlir::AttrTypeReplacer replacer = makeReplacer();
105 return replacer.replace(type);
106}
107
108LogicalResult PathVisitor::processPath(Location loc, hw::HierPathOp hierPathOp,
109 PathAttr &targetPath,
110 StringAttr &bottomModule,
111 StringAttr &component,
112 StringAttr &field) {
113 auto *context = hierPathOp->getContext();
114 // Look up the associated HierPathOp.
115 auto namepath = hierPathOp.getNamepathAttr().getValue();
116 SmallVector<PathElement> modules;
117
118 // Process the of the hierarchical path.
119 for (auto attr : namepath.drop_back()) {
120 auto innerRef = cast<hw::InnerRefAttr>(attr);
121 auto target = irn.lookup(innerRef);
122 assert(target.isOpOnly() && "can't target a port the middle of a namepath");
123 auto *op = target.getOp();
124 // Get the verilog name of the target.
125 auto verilogName = op->getAttrOfType<StringAttr>("hw.verilogName");
126 if (!verilogName && getOpNameFallback)
127 verilogName = getOpNameFallback(op);
128 if (!verilogName) {
129 auto diag = emitError(loc, "component does not have verilog name");
130 diag.attachNote(op->getLoc()) << "component here";
131 return diag;
132 }
133 modules.emplace_back(innerRef.getModule(), verilogName);
134 }
135
136 // Process the final target.
137 auto &end = namepath.back();
138 if (auto innerRef = dyn_cast<hw::InnerRefAttr>(end)) {
139 auto target = irn.lookup(innerRef);
140 if (target.isPort()) {
141 // We are targeting the port of a module.
142 auto module = cast<hw::HWModuleLike>(target.getOp());
143 auto index = target.getPort();
144 bottomModule = module.getModuleNameAttr();
145 component = StringAttr::get(context, module.getPortName(index));
146 auto loc = module.getPortLoc(index);
147 auto type = module.getPortTypes()[index];
148 if (failed(getAccessPath(loc, type, target.getField(), field)))
149 return failure();
150 } else {
151 auto *op = target.getOp();
152 assert(op && "innerRef should be targeting something");
153 // Get the current module.
154 auto currentModule = innerRef.getModule();
155 // Get the verilog name of the target.
156 auto verilogName = op->getAttrOfType<StringAttr>("hw.verilogName");
157 if (!verilogName && getOpNameFallback)
158 verilogName = getOpNameFallback(op);
159 if (!verilogName) {
160 auto diag = emitError(loc, "component does not have verilog name");
161 diag.attachNote(op->getLoc()) << "component here";
162 return diag;
163 }
164 // If this is our inner ref pair: [Foo::bar]
165 // if "bar" is an instance, modules = [Foo::bar], bottomModule = Bar.
166 // if "bar" is a wire, modules = [], bottomModule = Foo, component = bar.
167 if (auto inst = dyn_cast<hw::HWInstanceLike>(op)) {
168 // TODO: add support for instance choices.
169 auto mods = inst.getReferencedModuleNamesAttr();
170 if (mods.size() > 1)
171 return op->emitError("unsupported instance operation");
172 // We are targeting an instance.
173 modules.emplace_back(currentModule, verilogName);
174 bottomModule = cast<StringAttr>(mods[0]);
175 component = StringAttr::get(context, "");
176 field = StringAttr::get(context, "");
177 } else {
178 // We are targeting a regular component.
179 bottomModule = currentModule;
180 component = verilogName;
181 auto innerSym = cast<hw::InnerSymbolOpInterface>(op);
182 auto value = innerSym.getTargetResult();
183 if (failed(getAccessPath(value.getLoc(), value.getType(),
184 target.getField(), field)))
185 return failure();
186 }
187 }
188 } else {
189 // We are targeting a module.
190 auto symbolRef = cast<FlatSymbolRefAttr>(end);
191 bottomModule = symbolRef.getAttr();
192 component = StringAttr::get(context, "");
193 field = StringAttr::get(context, "");
194 }
195
196 // Create the target path.
197 targetPath = PathAttr::get(context, modules);
198 return success();
199}
200
201LogicalResult PathVisitor::process(PathCreateOp path) {
202 auto hierPathOp =
203 irn.symTable.lookup<hw::HierPathOp>(path.getTargetAttr().getAttr());
204 PathAttr targetPath;
205 StringAttr bottomModule;
206 StringAttr ref;
207 StringAttr field;
208 if (failed(processPath(path.getLoc(), hierPathOp, targetPath, bottomModule,
209 ref, field)))
210 return failure();
211
212 // Replace the old path operation.
213 OpBuilder builder(path);
214 auto frozenPath = FrozenPathCreateOp::create(
215 builder, path.getLoc(), path.getTargetKindAttr(), path->getOperand(0),
216 targetPath, bottomModule, ref, field);
217 path.replaceAllUsesWith(frozenPath.getResult());
218 path->erase();
219
220 return success();
221}
222
223LogicalResult PathVisitor::process(BasePathCreateOp path) {
224 auto hierPathOp =
225 irn.symTable.lookup<hw::HierPathOp>(path.getTargetAttr().getAttr());
226 PathAttr targetPath;
227 StringAttr bottomModule;
228 StringAttr ref;
229 StringAttr field;
230 if (failed(processPath(path.getLoc(), hierPathOp, targetPath, bottomModule,
231 ref, field)))
232 return failure();
233
234 if (!ref.empty())
235 return path->emitError("basepath must target an instance");
236 if (!field.empty())
237 return path->emitError("basepath must not target a field");
238
239 // Replace the old path operation.
240 OpBuilder builder(path);
241 auto frozenPath = FrozenBasePathCreateOp::create(
242 builder, path.getLoc(), path->getOperand(0), targetPath);
243 path.replaceAllUsesWith(frozenPath.getResult());
244 path->erase();
245
246 return success();
247}
248
249LogicalResult PathVisitor::process(EmptyPathOp path) {
250 OpBuilder builder(path);
251 auto frozenPath = FrozenEmptyPathOp::create(builder, path.getLoc());
252 path.replaceAllUsesWith(frozenPath.getResult());
253 path->erase();
254 return success();
255}
256
257LogicalResult PathVisitor::run(ModuleOp module) {
258 auto updatePathType = [&](Value value) {
259 if (hasPathType(value.getType()))
260 value.setType(processType(value.getType()));
261 };
262 auto replacer = makeReplacer();
263 for (auto classLike : module.getOps<ClassLike>()) {
264 // Transform PathType block argument to FrozenPathType.
265 for (auto arg : classLike.getBodyBlock()->getArguments())
266 updatePathType(arg);
267 auto result = classLike->walk([&](Operation *op) -> WalkResult {
268 if (auto basePath = dyn_cast<BasePathCreateOp>(op)) {
269 if (failed(process(basePath)))
270 return WalkResult::interrupt();
271 } else if (auto path = dyn_cast<PathCreateOp>(op)) {
272 if (failed(process(path)))
273 return WalkResult::interrupt();
274 } else if (auto path = dyn_cast<EmptyPathOp>(op)) {
275 if (failed(process(path)))
276 return WalkResult::interrupt();
277 } else if (isa<ListCreateOp, ListConcatOp, RegistryCreateOp,
278 ObjectFieldOp, UnknownValueOp>(op)) {
279 // Update result types in place to preserve attributes.
280 for (auto result : op->getResults())
281 updatePathType(result);
282 } else if (isa<ConstantOp>(op)) {
283 replacer.replaceElementsIn(op, /*replaceAttrs=*/true,
284 /*replaceLocs=*/false,
285 /*replaceTypes=*/true);
286 }
287 return WalkResult::advance();
288 });
289 if (result.wasInterrupted())
290 return failure();
291
292 // Transform field types
293 classLike.replaceFieldTypes(replacer);
294 }
295 return success();
296}
297
298namespace {
299struct FreezePathsPass
300 : public circt::om::impl::FreezePathsBase<FreezePathsPass> {
301 FreezePathsPass(std::function<StringAttr(Operation *)> getOpName)
302 : getOpName(std::move(getOpName)) {}
303 void runOnOperation() override;
304
305 std::function<StringAttr(Operation *)> getOpName;
306};
307} // namespace
308
309void FreezePathsPass::runOnOperation() {
310 auto module = getOperation();
311 auto &instanceGraph = getAnalysis<hw::InstanceGraph>();
312 mlir::SymbolTableCollection symbolTableCollection;
313 auto &symbolTable = getAnalysis<SymbolTable>();
314 hw::InnerSymbolTableCollection collection(module);
315 hw::InnerRefNamespace irn{symbolTable, collection};
316 if (failed(PathVisitor(instanceGraph, irn, getOpName).run(module)))
317 signalPassFailure();
318}
319
320std::unique_ptr<mlir::Pass> circt::om::createFreezePathsPass(
321 std::function<StringAttr(Operation *)> getOpName) {
322 return std::make_unique<FreezePathsPass>(getOpName);
323}
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static bool hasPathType(Type type)
static LogicalResult getAccessPath(Location loc, Type type, size_t fieldId, StringAttr &result)
mlir::AttrTypeReplacer makeReplacer()
static Type processType(Type type)
false return failure()
Parse an optional keyword or string and set instance into 'result'.
return success()
std::unique_ptr< mlir::Pass > createFreezePathsPass(std::function< StringAttr(Operation *)> getOpNameFallback={})
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
int run(Type[Generator] generator=CppGenerator, List[str] cmdline_args=sys.argv)
Definition om.py:1