CIRCT 24.0.0git
Loading...
Searching...
No Matches
ElaborateObject.cpp
Go to the documentation of this file.
1//===- ElaborateObject.cpp - OM compile-time evaluation pass --------------===//
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 performs evaluation of OM classes by inlining object
10// instantiations and folding field accesses. It replaces the runtime Evaluator
11// framework with static compile-time evaluation.
12//
13//===----------------------------------------------------------------------===//
14
18#include "circt/Support/LLVM.h"
19#include "mlir/IR/Builders.h"
20#include "mlir/IR/Diagnostics.h"
21#include "mlir/IR/IRMapping.h"
22#include "mlir/IR/Matchers.h"
23#include "mlir/IR/Operation.h"
24#include "mlir/IR/SymbolTable.h"
25#include "mlir/Interfaces/SideEffectInterfaces.h"
26#include "mlir/Support/WalkResult.h"
27#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/Support/LogicalResult.h"
30
31namespace circt {
32namespace om {
33#define GEN_PASS_DEF_ELABORATEOBJECT
34#include "circt/Dialect/OM/OMPasses.h.inc"
35} // namespace om
36} // namespace circt
37
38using namespace mlir;
39using namespace circt;
40using namespace om;
41
42namespace {
43// A map from (class name, field name) to field index.
44using FieldIndex = DenseMap<std::pair<StringAttr, StringAttr>, unsigned>;
45
46/// Pattern to inline ObjectOp instances by cloning the class body and
47/// replacing them with ElaboratedObjectOp.
48struct ObjectOpInliningPattern : public OpRewritePattern<ObjectOp> {
49 ObjectOpInliningPattern(MLIRContext *context, SymbolTable &symTable,
50 bool replaceExternalWithUnknown)
51 : OpRewritePattern<ObjectOp>(context), symTable(symTable),
52 replaceExternalWithUnknown(replaceExternalWithUnknown) {}
53
54 LogicalResult matchAndRewrite(ObjectOp objOp,
55 PatternRewriter &rewriter) const override {
56 auto classLike =
57 symTable.lookup<ClassLike>(objOp.getClassNameAttr().getAttr());
58 assert(classLike);
59
60 // External classes cannot be elaborated; replace with unknown values.
61 if (isa<ClassExternOp>(classLike)) {
62 if (!replaceExternalWithUnknown)
63 return failure();
64 rewriter.replaceOpWithNewOp<UnknownValueOp>(objOp, objOp.getType());
65 return success();
66 }
67
68 auto classOp = dyn_cast<ClassOp>(classLike.getOperation());
69 if (!classOp)
70 return failure();
71
72 IRMapping mapper;
73 for (auto [formal, actual] : llvm::zip(
74 classOp.getBodyBlock()->getArguments(), objOp.getActualParams()))
75 mapper.map(formal, actual);
76
77 // Clone the class body into a temporary region with argument substitution.
78 Region clonedRegion;
79 classOp.getBody().cloneInto(&clonedRegion, mapper);
80 Block *clonedBlock = &clonedRegion.front();
81
82 auto clonedFields = cast<ClassFieldsOp>(clonedBlock->getTerminator());
83 SmallVector<Value> fieldValues(clonedFields.getFields());
84 // Propagate the class's per-field locations onto each field value, fused
85 // with the value's existing location.
86 if (auto classOp = dyn_cast<ClassOp>(classLike.getOperation()))
87 for (auto [i, v] : llvm::enumerate(fieldValues))
88 v.setLoc(
89 rewriter.getFusedLoc({classOp.getFieldLocByIndex(i), v.getLoc()}));
90
91 // Erase the terminator and inline the body at the object instantiation.
92 rewriter.eraseOp(clonedFields);
93 rewriter.inlineBlockBefore(clonedBlock, objOp);
94
95 rewriter.replaceOpWithNewOp<ElaboratedObjectOp>(objOp, classLike,
96 fieldValues);
97
98 return success();
99 }
100
101 const SymbolTable &symTable;
102 bool replaceExternalWithUnknown;
103};
104
105/// Pattern to fold ObjectFieldOp on ElaboratedObjectOp by directly accessing
106/// the field value operands.
107struct EvaluateObjectField : OpRewritePattern<ObjectFieldOp> {
108 EvaluateObjectField(MLIRContext *context, const SymbolTable &symTable,
109 const FieldIndex &fieldIndexes)
110 : OpRewritePattern<ObjectFieldOp>(context), symTable(symTable),
111 fieldIndexes(fieldIndexes) {}
112
113 LogicalResult matchAndRewrite(ObjectFieldOp op,
114 PatternRewriter &rewriter) const override {
115 // Only fold if the object is an ElaboratedObjectOp.
116 auto elaboratedOp = op.getObject().getDefiningOp<ElaboratedObjectOp>();
117 if (!elaboratedOp)
118 return failure();
119
120 auto classLike =
121 symTable.lookup<ClassLike>(elaboratedOp.getClassNameAttr().getAttr());
122 assert(classLike);
123
124 // Find the field index and get the corresponding value.
125 auto index =
126 fieldIndexes.at({classLike.getSymNameAttr(), op.getFieldAttr()});
127 auto result = elaboratedOp.getFieldValues()[index];
128
129 // Skip cycles where a field references itself.
130 // This will be raised as an error later.
131 if (op.getResult() == result)
132 return failure();
133
134 rewriter.replaceOp(op, result);
135 return success();
136 }
137
138 const SymbolTable &symTable;
139 const FieldIndex &fieldIndexes;
140};
141
142/// Pattern to propagate UnknownValueOp through pure OM operations.
143/// If any operand is unknown, all results become unknown.
144struct UnknownPropagationPattern : RewritePattern {
145 UnknownPropagationPattern(MLIRContext *context)
146 : RewritePattern(MatchAnyOpTypeTag(), /*benefit=*/1, context) {}
147
148 LogicalResult matchAndRewrite(Operation *op,
149 PatternRewriter &rewriter) const override {
150 // Only target pure OM operations.
151 // TODO: Consider add a trait for this if we want to have more explict
152 // behavior.
153 if (!isa_and_nonnull<OMDialect>(op->getDialect()) || !isPure(op) ||
154 op->getNumResults() == 0)
155 return failure();
156
157 // Check if any operand is an UnknownValueOp.
158 // TODO: This directly ports the existing Evaluator semantics, but it
159 // causes inconsistent evaluation for operations that can reason about
160 // known values, e.g., "and(0, unknown) -> 0".
161 if (!llvm::any_of(op->getOperands(), [](Value operand) {
162 return operand.getDefiningOp<UnknownValueOp>();
163 }))
164 return failure();
165
166 // Replace all results with UnknownValueOp.
167 SmallVector<Value> unknowns;
168 for (Type resultType : op->getResultTypes())
169 unknowns.push_back(
170 UnknownValueOp::create(rewriter, op->getLoc(), resultType));
171
172 rewriter.replaceOp(op, unknowns);
173 return success();
174 }
175};
176
177// Check if an operation can be evaluated at compile time and is valid to
178// remain in the IR after elaboration.
179bool isFullyEvaluated(Operation *op) {
180 return isa<
181 // Structure.
182 ClassOp, ClassFieldsOp, ElaboratedObjectOp, AnyCastOp,
183 // Constant-like.
184 ConstantOp, UnknownValueOp,
185 // Path.
186 FrozenBasePathCreateOp, FrozenPathCreateOp, FrozenEmptyPathOp,
187 // List.
188 ListCreateOp, ListConcatOp>(op);
189}
190
191LogicalResult verifyResult(ClassOp module, bool allowUnevaluated) {
192 auto isLegal = [allowUnevaluated](Operation *op) -> LogicalResult {
193 // Check assert satisfied.
194 if (auto assertOp = dyn_cast<PropertyAssertOp>(op)) {
195 // Check if the condition is a constant false, which means the assertion
196 // is violated.
197 auto *defOp = assertOp.getCondition().getDefiningOp();
198 APInt value;
199 auto checkAssert = [&](bool cond) -> LogicalResult {
200 if (cond) {
201 // Erase when success, serialization doesn't need to care about
202 // this.
203 op->erase();
204 return success();
205 }
206
207 // The message is supposed to be fully evaluated at this point, though
208 // it could be unknown.
209 auto messageOp =
210 dyn_cast_or_null<ConstantOp>(assertOp.getMessage().getDefiningOp());
211 if (!messageOp) {
212 if (allowUnevaluated)
213 return op->emitError("OM property assertion failed: <unevaluated>");
214
215 auto diag = emitError(op->getLoc(),
216 "OM property assertion failed, but no message "
217 "is available as the message is unevaluated");
218 diag.attachNote(assertOp.getMessage().getLoc())
219 << "unevaluated message operation is here";
220 return failure();
221 }
222
223 StringAttr message;
224 if (!matchPattern(assertOp.getMessage(), m_Constant(&message)))
225 return op->emitError()
226 << "OM property assertion failed, but no message is available "
227 "because the message is not a constant string";
228 return op->emitError("OM property assertion failed: ")
229 << message.getValue();
230 };
231
232 // Condition is a constant integer/bool - check if it's true.
233 if (matchPattern(assertOp.getCondition(), m_ConstantInt(&value)))
234 return checkAssert(!value.isZero());
235
236 // Condition is unknown - treat as passing.
237 if (auto unknownOp = dyn_cast_or_null<UnknownValueOp>(defOp))
238 return checkAssert(true);
239
240 // This means the condition was not fully evaluated.
241 if (allowUnevaluated)
242 return success();
243 return emitError(op->getLoc(), "failed to evaluate assertion condition");
244 }
245
246 if (!isFullyEvaluated(op)) {
247 if (allowUnevaluated)
248 return success();
249 return emitError(op->getLoc()) << "failed to evaluate " << op->getName();
250 }
251
252 return success();
253 };
254 bool encounteredError = false;
255 module.walk([&](Operation *op) { encounteredError |= failed(isLegal(op)); });
256
257 return failure(encounteredError);
258}
259
260struct ElaborateObjectPass
261 : public circt::om::impl::ElaborateObjectBase<ElaborateObjectPass> {
262 using Base::Base;
263
264 static LogicalResult elaborateClass(ClassOp classOp, SymbolTable &symTable,
265 FieldIndex &fieldIndexes,
266 bool allowUnevaluated = false) {
267 // Elaborate objects by inlining all ObjectOps and folding field accesses
268 // using a greedy pattern rewriter. NOTE: The conversion framework is not
269 // suitable here because inlining patterns need to be applied recursively to
270 // fully evaluate nested object instantiations.
271 RewritePatternSet patterns(classOp.getContext());
272 patterns.add<ObjectOpInliningPattern>(classOp.getContext(), symTable,
273 !allowUnevaluated);
274 patterns.add<EvaluateObjectField>(classOp.getContext(), symTable,
275 fieldIndexes);
276 patterns.add<UnknownPropagationPattern>(classOp.getContext());
277 GreedyRewriteConfig config;
278 // Disable iteration limit to allow full recursive inlining.
279 config.setMaxIterations(GreedyRewriteConfig::kNoLimit);
280 if (failed(applyPatternsGreedily(classOp, std::move(patterns), config)))
281 return failure();
282
283 // Check if elaboration succeeded after saturation.
284 return verifyResult(classOp, allowUnevaluated);
285 }
286
287 LogicalResult initialize(MLIRContext *context) override {
288 unsigned numModes =
289 allPublicClasses.getValue() + !targetClass.getValue().empty();
290 if (numModes != 1)
291 return emitError(UnknownLoc::get(context))
292 << "exactly one of 'target-class' or 'all-public-classes' must "
293 "be specified";
294 return success();
295 }
296
297 void runOnOperation() override {
298 auto module = getOperation();
299 auto &symTable = getAnalysis<SymbolTable>();
300
301 // Build a map from (class name, field name) to field index for all
302 // classes.
303 FieldIndex fieldIndexes;
304 for (auto classOp : module.getOps<ClassLike>()) {
305 auto name = classOp.getSymNameAttr();
306 for (auto [idx, fieldName] :
307 llvm::enumerate(classOp.getFieldNames().getAsRange<StringAttr>()))
308 fieldIndexes[{name, fieldName}] = idx;
309 }
310
311 // Elaborate all public classes.
312 if (allPublicClasses) {
313 for (auto classOp : module.getOps<ClassOp>()) {
314 if (!classOp.isPublic())
315 continue;
316 if (failed(elaborateClass(classOp, symTable, fieldIndexes,
317 allowUnevaluated)))
318 return signalPassFailure();
319 }
320 return;
321 }
322
323 // Normal mode: elaborate the specified target class.
324 auto classOp = symTable.lookup<ClassOp>(targetClass);
325 if (!classOp) {
326 emitError(module.getLoc())
327 << "target class '" << targetClass << "' was not found";
328 return signalPassFailure();
329 }
330
331 if (failed(
332 elaborateClass(classOp, symTable, fieldIndexes, allowUnevaluated)))
333 return signalPassFailure();
334 }
335};
336
337} // namespace
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static Location getLoc(DefSlot slot)
Definition Mem2Reg.cpp:222
static Block * getBodyBlock(FModuleLike mod)
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Definition om.py:1