CIRCT 24.0.0git
Loading...
Searching...
No Matches
HWLegalizeModules.cpp
Go to the documentation of this file.
1//===- HWLegalizeModulesPass.cpp - Lower unsupported IR features away -----===//
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 pass lowers away features in the SV/Comb/HW dialects that are
10// unsupported by some tools (e.g. multidimensional arrays) as specified by
11// LoweringOptions. This pass is run relatively late in the pipeline in
12// preparation for emission. Any passes run after this (e.g. PrettifyVerilog)
13// must be aware they cannot introduce new invalid constructs.
14//
15//===----------------------------------------------------------------------===//
16
24#include "mlir/IR/Builders.h"
25#include "mlir/Pass/Pass.h"
26
27namespace circt {
28namespace sv {
29#define GEN_PASS_DEF_HWLEGALIZEMODULES
30#include "circt/Dialect/SV/SVPasses.h.inc"
31} // namespace sv
32} // namespace circt
33
34using namespace circt;
35//===----------------------------------------------------------------------===//
36// HWLegalizeModulesPass
37//===----------------------------------------------------------------------===//
38
39namespace {
40struct HWLegalizeModulesPass
41 : public circt::sv::impl::HWLegalizeModulesBase<HWLegalizeModulesPass> {
42 void runOnOperation() override;
43
44private:
45 void processPostOrder(Block &block);
46 bool tryLoweringPackedArrayOp(Operation &op);
47 template <typename ElementType>
48 SmallVector<std::pair<Value, Value>>
49 createIndexValuePairs(OpBuilder &builder, LocationAttr loc, hw::ArrayType ty,
50 Value array);
51 Value lowerLookupToCasez(Operation &op, Value input, Value index,
52 mlir::Type elementType,
53 SmallVector<Value> caseValues);
54 bool processUsers(Operation &op, Value value, ArrayRef<Value> mapping);
55 template <typename DeclOp>
56 bool lowerArrayVar(DeclOp declOp);
57 std::optional<std::pair<uint64_t, unsigned>>
58 tryExtractIndexAndBitWidth(Value value);
59 bool tryLoweringClockedAssertLike(Operation &op);
60
61 /// This is the current hw.module being processed.
62 hw::HWModuleOp thisHWModule;
63
64 bool anythingChanged;
65
66 /// This tells us what language features we're allowed to use in generated
67 /// Verilog.
68 LoweringOptions options;
69
70 /// This pass will be run on multiple hw.modules, this keeps track of the
71 /// contents of LoweringOptions so we don't have to reparse the
72 /// LoweringOptions for every hw.module.
73 StringAttr lastParsedOptions;
74};
75} // end anonymous namespace
76
77/// Transform an array-typed sv.var or sv.reg into individual declarations
78/// of the same kind for each array element.
79template <typename DeclOp>
80bool HWLegalizeModulesPass::lowerArrayVar(DeclOp declOp) {
81 auto ty = hw::type_dyn_cast<hw::ArrayType>(declOp.getElementType());
82 if (!ty)
83 return false;
84
85 OpBuilder builder(declOp);
86 auto name = StringAttr::get(declOp.getContext(), "name");
87 SmallVector<Value> elements;
88 for (size_t i = 0, e = ty.getNumElements(); i < e; i++) {
89 auto loc = declOp.getLoc();
90 auto element = DeclOp::create(builder, loc, ty.getElementType());
91 if (auto nameAttr = declOp->template getAttrOfType<StringAttr>(name)) {
92 element.setNameAttr(
93 StringAttr::get(declOp.getContext(), nameAttr.getValue()));
94 }
95 elements.push_back(element);
96 }
97
98 // Fix users to refer to individual element decls.
99 return processUsers(*declOp, declOp.getResult(), elements);
100}
101
102bool HWLegalizeModulesPass::tryLoweringPackedArrayOp(Operation &op) {
103 return TypeSwitch<Operation *, bool>(&op)
104 .Case<hw::AggregateConstantOp>([&](hw::AggregateConstantOp constOp) {
105 // Replace individual element uses (if any) with input fields.
106 SmallVector<Value> inputs;
107 OpBuilder builder(constOp);
108 for (auto field : llvm::reverse(constOp.getFields())) {
109 if (auto intAttr = dyn_cast<IntegerAttr>(field))
110 inputs.push_back(
111 hw::ConstantOp::create(builder, constOp.getLoc(), intAttr));
112 else
113 inputs.push_back(hw::AggregateConstantOp::create(
114 builder, constOp.getLoc(), constOp.getType(),
115 cast<ArrayAttr>(field)));
116 }
117 if (!processUsers(op, constOp.getResult(), inputs))
118 return false;
119
120 // Remove original op.
121 return true;
122 })
123 .Case<hw::ArrayConcatOp>([&](hw::ArrayConcatOp concatOp) {
124 // Redirect individual element uses (if any) to the input arguments.
125 SmallVector<Value> values;
126 OpBuilder builder(concatOp);
127 for (auto array : llvm::reverse(concatOp.getInputs())) {
128 auto ty = hw::type_cast<hw::ArrayType>(array.getType());
129 const auto indexValues = createIndexValuePairs<hw::ArrayGetOp>(
130 builder, concatOp.getLoc(), ty, array);
131 for (const auto &[_, value] : indexValues) {
132 values.push_back(value);
133 }
134 }
135 if (!processUsers(op, concatOp.getResult(), values))
136 return false;
137
138 // Remove original op.
139 return true;
140 })
141 .Case<hw::ArrayCreateOp>([&](hw::ArrayCreateOp createOp) {
142 // Replace individual element uses (if any) with input arguments.
143 SmallVector<Value> inputs(llvm::reverse(createOp.getInputs()));
144 if (!processUsers(op, createOp.getResult(), inputs))
145 return false;
146
147 // Remove original op.
148 return true;
149 })
150 .Case<hw::ArrayGetOp>([&](hw::ArrayGetOp getOp) {
151 // Skip index ops with constant index.
152 auto index = getOp.getIndex();
153 if (auto *definingOp = index.getDefiningOp())
154 if (isa<hw::ConstantOp>(definingOp))
155 return false;
156
157 // Generate case value element lookups.
158 auto ty = hw::type_cast<hw::ArrayType>(getOp.getInput().getType());
159 OpBuilder builder(getOp);
160 auto loc = op.getLoc();
161 const auto indexValues = createIndexValuePairs<hw::ArrayGetOp>(
162 builder, loc, ty, getOp.getInput());
163 SmallVector<Value> caseValues;
164 for (const auto &[_, value] : indexValues)
165 caseValues.push_back(value);
166
167 // Transform array index op into casez statement.
168 auto theWire = lowerLookupToCasez(op, getOp.getInput(), index,
169 ty.getElementType(), caseValues);
170
171 // Emit the read from the wire, replace uses and clean up.
172 builder.setInsertionPoint(getOp);
173 auto readWire =
174 sv::ReadInOutOp::create(builder, getOp.getLoc(), theWire);
175 getOp.getResult().replaceAllUsesWith(readWire);
176 return true;
177 })
178 .Case<sv::ArrayIndexInOutOp>([&](sv::ArrayIndexInOutOp indexOp) {
179 // Skip index ops with constant index.
180 auto index = indexOp.getIndex();
181 if (auto *definingOp = index.getDefiningOp())
182 if (isa<hw::ConstantOp>(definingOp))
183 return false;
184
185 // Skip index ops with unpacked arrays.
186 auto handle = indexOp.getInput().getType();
187 Type elementType = sv::getHandleElementType(handle);
188 if (hw::type_isa<hw::UnpackedArrayType>(elementType))
189 return false;
190
191 // Generate case value element lookups.
192 auto ty = hw::type_cast<hw::ArrayType>(elementType);
193 OpBuilder builder(&op);
194 auto loc = op.getLoc();
195 const auto indexValues = createIndexValuePairs<sv::ArrayIndexInOutOp>(
196 builder, loc, ty, indexOp.getInput());
197 SmallVector<Value> caseValues;
198 for (const auto &[_, element] : indexValues) {
199 auto readElement = sv::ReadInOutOp::create(builder, loc, element);
200 caseValues.push_back(readElement);
201 }
202
203 // Transform array index op into casez statement.
204 auto theWire = lowerLookupToCasez(op, indexOp.getInput(), index,
205 ty.getElementType(), caseValues);
206
207 // Replace uses and clean up.
208 indexOp.getResult().replaceAllUsesWith(theWire);
209 return true;
210 })
211 .Case<sv::PAssignOp>([&](sv::PAssignOp assignOp) {
212 // Transform array assignment into individual assignments for each array
213 // element.
214 auto destElementType =
215 sv::getHandleElementType(assignOp.getDest().getType());
216 auto ty = hw::type_dyn_cast<hw::ArrayType>(destElementType);
217 if (!ty)
218 return false;
219
220 OpBuilder builder(assignOp);
221 auto loc = op.getLoc();
222 const auto indexValues = createIndexValuePairs<hw::ArrayGetOp>(
223 builder, loc, ty, assignOp.getSrc());
224 for (const auto &[index, srcElement] : indexValues) {
225 auto dstElement = sv::ArrayIndexInOutOp::create(
226 builder, loc, assignOp.getDest(), index);
227 sv::PAssignOp::create(builder, loc, dstElement, srcElement);
228 }
229
230 // Remove original assignment.
231 return true;
232 })
233 .Case<sv::VarOp, sv::RegOp>([&](auto op) { return lowerArrayVar(op); })
234 .Case<comb::MuxOp>([&](comb::MuxOp muxOp) {
235 // Transform array mux into individual element muxes.
236 auto ty = hw::type_dyn_cast<hw::ArrayType>(muxOp.getType());
237 if (!ty)
238 return false;
239
240 OpBuilder builder(muxOp);
241
242 auto trueValues = createIndexValuePairs<hw::ArrayGetOp>(
243 builder, muxOp.getLoc(), ty, muxOp.getTrueValue());
244 auto falseValues = createIndexValuePairs<hw::ArrayGetOp>(
245 builder, muxOp.getLoc(), ty, muxOp.getFalseValue());
246
247 SmallVector<Value> muxedValues;
248
249 for (size_t i = 0, e = trueValues.size(); i < e; i++) {
250 const auto &[trueIndex, trueValue] = trueValues[i];
251 const auto &[falseIndex, falseValue] = falseValues[i];
252 muxedValues.push_back(
253 comb::MuxOp::create(builder, muxOp.getLoc(), muxOp.getCond(),
254 trueValue, falseValue, muxOp.getTwoState()));
255 }
256
257 if (!processUsers(op, muxOp.getResult(), muxedValues))
258 return false;
259
260 // Remove original mux.
261 return true;
262 })
263 .Default([&](auto op) { return false; });
264}
265
266template <typename ElementType>
267SmallVector<std::pair<Value, Value>>
268HWLegalizeModulesPass::createIndexValuePairs(OpBuilder &builder,
269 LocationAttr loc, hw::ArrayType ty,
270 Value array) {
271 SmallVector<std::pair<Value, Value>> result;
272 for (size_t i = 0, e = ty.getNumElements(); i < e; i++) {
273 auto index = builder.createOrFold<hw::ConstantOp>(
274 loc, APInt(llvm::Log2_64_Ceil(e), i));
275 auto element = ElementType::create(builder, loc, array, index);
276 result.emplace_back(index, element);
277 }
278 return result;
279}
280
281Value HWLegalizeModulesPass::lowerLookupToCasez(Operation &op, Value input,
282 Value index,
283 mlir::Type elementType,
284 SmallVector<Value> caseValues) {
285 // Create the wire for the result of the casez in the
286 // hw.module.
287 OpBuilder builder(&op);
288 auto theWire = sv::VarOp::create(builder, op.getLoc(), elementType,
289 builder.getStringAttr("casez_tmp"));
290 builder.setInsertionPoint(&op);
291
292 auto loc = input.getLoc();
293 // A casez is a procedural operation, so if we're in a
294 // non-procedural region we need to inject an always_comb
295 // block.
296 if (!op.getParentOp()->hasTrait<ProceduralRegion>()) {
297 auto alwaysComb = sv::AlwaysCombOp::create(builder, loc);
298 builder.setInsertionPointToEnd(alwaysComb.getBodyBlock());
299 }
300
301 // If we are missing elements in the array (it is non-power of
302 // two), then add a default 'X' value.
303 if (1ULL << index.getType().getIntOrFloatBitWidth() != caseValues.size()) {
304 caseValues.push_back(sv::ConstantXOp::create(builder, op.getLoc(),
305 op.getResult(0).getType()));
306 }
307
308 APInt caseValue(index.getType().getIntOrFloatBitWidth(), 0);
309 auto *context = builder.getContext();
310
311 // Create the casez itself.
312 sv::CaseOp::create(
313 builder, loc, CaseStmtType::CaseZStmt, index, caseValues.size(),
314 [&](size_t caseIdx) -> std::unique_ptr<sv::CasePattern> {
315 // Use a default pattern for the last value, even if we
316 // are complete. This avoids tools thinking they need to
317 // insert a latch due to potentially incomplete case
318 // coverage.
319 bool isDefault = caseIdx == caseValues.size() - 1;
320 Value theValue = caseValues[caseIdx];
321 std::unique_ptr<sv::CasePattern> thePattern;
322
323 if (isDefault)
324 thePattern = std::make_unique<sv::CaseDefaultPattern>(context);
325 else
326 thePattern = std::make_unique<sv::CaseBitPattern>(caseValue, context);
327 ++caseValue;
328 sv::BPAssignOp::create(builder, loc, theWire, theValue);
329 return thePattern;
330 });
331
332 return theWire;
333}
334
335bool HWLegalizeModulesPass::processUsers(Operation &op, Value value,
336 ArrayRef<Value> mapping) {
337 for (auto *user : llvm::make_early_inc_range(value.getUsers())) {
338 if (TypeSwitch<Operation *, bool>(user)
339 .Case<hw::ArrayGetOp>([&](hw::ArrayGetOp getOp) {
340 if (auto indexAndBitWidth =
341 tryExtractIndexAndBitWidth(getOp.getIndex())) {
342 getOp.replaceAllUsesWith(mapping[indexAndBitWidth->first]);
343 return true;
344 }
345
346 return false;
347 })
348 .Case<sv::ArrayIndexInOutOp>([&](sv::ArrayIndexInOutOp indexOp) {
349 if (auto indexAndBitWidth =
350 tryExtractIndexAndBitWidth(indexOp.getIndex())) {
351 indexOp.replaceAllUsesWith(mapping[indexAndBitWidth->first]);
352 return true;
353 }
354
355 return false;
356 })
357 .Default([](auto op) { return false; })) {
358 user->erase();
359 continue;
360 }
361
362 user->emitError("unsupported packed array expression");
363 signalPassFailure();
364 return false;
365 }
366
367 return true;
368}
369
370std::optional<std::pair<uint64_t, unsigned>>
371HWLegalizeModulesPass::tryExtractIndexAndBitWidth(Value value) {
372 if (auto constantOp = dyn_cast<hw::ConstantOp>(value.getDefiningOp())) {
373 auto index = constantOp.getValue();
374 return std::make_optional(
375 std::make_pair(index.getZExtValue(), index.getBitWidth()));
376 }
377 return std::nullopt;
378}
379
380namespace {
381template <typename Op>
382bool tryLoweringClockedAssertLike(Op &op) {
383 auto event = op.getEvent();
384 if (!event.has_value())
385 return false;
386
387 OpBuilder builder(op);
388
389 sv::AlwaysOp::create(builder, op->getLoc(), *event, op.getClock(), [&] {
390 Op::create(builder, op.getLoc(), op.getProperty(), op.getDisable(),
391 op.getLabelAttr());
392 });
393 return true;
394}
395} // namespace
396
397bool HWLegalizeModulesPass::tryLoweringClockedAssertLike(Operation &op) {
398 return TypeSwitch<Operation *, bool>(&op)
399 .Case<sv::AssertPropertyOp>(
400 ::tryLoweringClockedAssertLike<sv::AssertPropertyOp>)
401 .Case<sv::AssumePropertyOp>(
402 ::tryLoweringClockedAssertLike<sv::AssumePropertyOp>)
403 .Case<sv::CoverPropertyOp>(
404 ::tryLoweringClockedAssertLike<sv::CoverPropertyOp>)
405 .Default([&](auto op) { return false; });
406}
407
408void HWLegalizeModulesPass::processPostOrder(Block &body) {
409 if (body.empty())
410 return;
411
412 // Walk the block bottom-up, processing the region tree inside out.
413 Block::iterator it = std::prev(body.end());
414 while (it != body.end()) {
415 auto &op = *it;
416
417 // Advance the iterator, using the end iterator as a sentinel that we're at
418 // the top of the block.
419 if (it == body.begin())
420 it = body.end();
421 else
422 --it;
423
424 if (op.getNumRegions()) {
425 for (auto &region : op.getRegions())
426 for (auto &regionBlock : region.getBlocks())
427 processPostOrder(regionBlock);
428 }
429
430 if (options.disallowPackedArrays) {
431 // Try supported packed array op lowering.
432 if (tryLoweringPackedArrayOp(op)) {
433 it = --Block::iterator(op);
434 op.erase();
435 anythingChanged = true;
436 continue;
437 }
438
439 // Otherwise, if the IR produces a packed array and we aren't allowing
440 // multi-dimensional arrays, reject the IR as invalid.
441 for (auto value : op.getResults()) {
442 if (isa<hw::ArrayType>(value.getType())) {
443 op.emitError("unsupported packed array expression");
444 signalPassFailure();
445 }
446 }
447 }
448
449 if (options.disallowClockedAssertions) {
450 if (tryLoweringClockedAssertLike(op)) {
451 op.erase();
452 anythingChanged = true;
453 continue;
454 }
455 }
456 }
457}
458
459void HWLegalizeModulesPass::runOnOperation() {
460 thisHWModule = getOperation();
461
462 // Parse the lowering options if necessary.
463 auto optionsAttr = LoweringOptions::getAttributeFrom(
464 cast<ModuleOp>(thisHWModule->getParentOp()));
465 if (optionsAttr != lastParsedOptions) {
466 if (optionsAttr)
467 options = LoweringOptions(optionsAttr.getValue(), [&](Twine error) {
468 thisHWModule.emitError(error);
469 });
470 else
471 options = LoweringOptions();
472 lastParsedOptions = optionsAttr;
473 }
474
475 // Keeps track if anything changed during this pass, used to determine if
476 // the analyses were preserved.
477 anythingChanged = false;
478
479 // Walk the operations in post-order, transforming any that are interesting.
480 processPostOrder(*thisHWModule.getBodyBlock());
481
482 // If we did not change anything in the IR mark all analysis as preserved.
483 if (!anythingChanged)
484 markAllAnalysesPreserved();
485}
MlirType elementType
Definition CHIRRTL.cpp:29
static std::unique_ptr< Context > context
create(data_type, value)
Definition hw.py:433
create(value)
Definition sv.py:151
create(data_type, name=None, sym_name=None)
Definition sv.py:125
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
bool disallowPackedArrays
If true, eliminate packed arrays for tools that don't support them (e.g.
static mlir::StringAttr getAttributeFrom(mlir::ModuleOp module)
Return the value of the circt.loweringOptions in the specified module if present, or a null attribute...