Loading [MathJax]/extensions/tex2jax.js
CIRCT 22.0.0git
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
VerifToSMT.cpp
Go to the documentation of this file.
1//===- VerifToSMT.cpp -----------------------------------------------------===//
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
14#include "mlir/Conversion/ReconcileUnrealizedCasts/ReconcileUnrealizedCasts.h"
15#include "mlir/Dialect/Arith/IR/Arith.h"
16#include "mlir/Dialect/Func/IR/FuncOps.h"
17#include "mlir/Dialect/SCF/IR/SCF.h"
18#include "mlir/Dialect/SMT/IR/SMTOps.h"
19#include "mlir/Dialect/SMT/IR/SMTTypes.h"
20#include "mlir/IR/ValueRange.h"
21#include "mlir/Pass/Pass.h"
22#include "mlir/Transforms/DialectConversion.h"
23#include "llvm/ADT/SmallVector.h"
24
25namespace circt {
26#define GEN_PASS_DEF_CONVERTVERIFTOSMT
27#include "circt/Conversion/Passes.h.inc"
28} // namespace circt
29
30using namespace mlir;
31using namespace circt;
32using namespace hw;
33
34//===----------------------------------------------------------------------===//
35// Conversion patterns
36//===----------------------------------------------------------------------===//
37
38namespace {
39/// Lower a verif::AssertOp operation with an i1 operand to a smt::AssertOp,
40/// negated to check for unsatisfiability.
41struct VerifAssertOpConversion : OpConversionPattern<verif::AssertOp> {
42 using OpConversionPattern<verif::AssertOp>::OpConversionPattern;
43
44 LogicalResult
45 matchAndRewrite(verif::AssertOp op, OpAdaptor adaptor,
46 ConversionPatternRewriter &rewriter) const override {
47 Value cond = typeConverter->materializeTargetConversion(
48 rewriter, op.getLoc(), smt::BoolType::get(getContext()),
49 adaptor.getProperty());
50 Value notCond = smt::NotOp::create(rewriter, op.getLoc(), cond);
51 rewriter.replaceOpWithNewOp<smt::AssertOp>(op, notCond);
52 return success();
53 }
54};
55
56/// Lower a verif::AssumeOp operation with an i1 operand to a smt::AssertOp
57struct VerifAssumeOpConversion : OpConversionPattern<verif::AssumeOp> {
58 using OpConversionPattern<verif::AssumeOp>::OpConversionPattern;
59
60 LogicalResult
61 matchAndRewrite(verif::AssumeOp op, OpAdaptor adaptor,
62 ConversionPatternRewriter &rewriter) const override {
63 Value cond = typeConverter->materializeTargetConversion(
64 rewriter, op.getLoc(), smt::BoolType::get(getContext()),
65 adaptor.getProperty());
66 rewriter.replaceOpWithNewOp<smt::AssertOp>(op, cond);
67 return success();
68 }
69};
70
71template <typename OpTy>
72struct CircuitRelationCheckOpConversion : public OpConversionPattern<OpTy> {
74
75protected:
76 using ConversionPattern::typeConverter;
77 void
78 createOutputsDifferentOps(Operation *firstOutputs, Operation *secondOutputs,
79 Location &loc, ConversionPatternRewriter &rewriter,
80 SmallVectorImpl<Value> &outputsDifferent) const {
81 // Convert the yielded values back to the source type system (since
82 // the operations of the inlined blocks will be converted by other patterns
83 // later on and we should make sure the IR is well-typed after each pattern
84 // application), and compare the output values.
85 for (auto [out1, out2] :
86 llvm::zip(firstOutputs->getOperands(), secondOutputs->getOperands())) {
87 Value o1 = typeConverter->materializeTargetConversion(
88 rewriter, loc, typeConverter->convertType(out1.getType()), out1);
89 Value o2 = typeConverter->materializeTargetConversion(
90 rewriter, loc, typeConverter->convertType(out1.getType()), out2);
91 outputsDifferent.emplace_back(
92 smt::DistinctOp::create(rewriter, loc, o1, o2));
93 }
94 }
95
96 void replaceOpWithSatCheck(OpTy &op, Location &loc,
97 ConversionPatternRewriter &rewriter,
98 smt::SolverOp &solver) const {
99 // If no operation uses the result of this solver, we leave our check
100 // operations empty. If the result is used, we create a check operation with
101 // the result type of the operation and yield the result of the check
102 // operation.
103 if (op.getNumResults() == 0) {
104 auto checkOp = smt::CheckOp::create(rewriter, loc, TypeRange{});
105 rewriter.createBlock(&checkOp.getSatRegion());
106 smt::YieldOp::create(rewriter, loc);
107 rewriter.createBlock(&checkOp.getUnknownRegion());
108 smt::YieldOp::create(rewriter, loc);
109 rewriter.createBlock(&checkOp.getUnsatRegion());
110 smt::YieldOp::create(rewriter, loc);
111 rewriter.setInsertionPointAfter(checkOp);
112 smt::YieldOp::create(rewriter, loc);
113
114 // Erase as operation is replaced by an operator without a return value.
115 rewriter.eraseOp(op);
116 } else {
117 Value falseVal =
118 arith::ConstantOp::create(rewriter, loc, rewriter.getBoolAttr(false));
119 Value trueVal =
120 arith::ConstantOp::create(rewriter, loc, rewriter.getBoolAttr(true));
121 auto checkOp = smt::CheckOp::create(rewriter, loc, rewriter.getI1Type());
122 rewriter.createBlock(&checkOp.getSatRegion());
123 smt::YieldOp::create(rewriter, loc, falseVal);
124 rewriter.createBlock(&checkOp.getUnknownRegion());
125 smt::YieldOp::create(rewriter, loc, falseVal);
126 rewriter.createBlock(&checkOp.getUnsatRegion());
127 smt::YieldOp::create(rewriter, loc, trueVal);
128 rewriter.setInsertionPointAfter(checkOp);
129 smt::YieldOp::create(rewriter, loc, checkOp->getResults());
130
131 rewriter.replaceOp(op, solver->getResults());
132 }
133 }
134};
135
136/// Lower a verif::LecOp operation to a miter circuit encoded in SMT.
137/// More information on miter circuits can be found, e.g., in this paper:
138/// Brand, D., 1993, November. Verification of large synthesized designs. In
139/// Proceedings of 1993 International Conference on Computer Aided Design
140/// (ICCAD) (pp. 534-537). IEEE.
141struct LogicEquivalenceCheckingOpConversion
142 : CircuitRelationCheckOpConversion<verif::LogicEquivalenceCheckingOp> {
143 using CircuitRelationCheckOpConversion<
144 verif::LogicEquivalenceCheckingOp>::CircuitRelationCheckOpConversion;
145
146 LogicalResult
147 matchAndRewrite(verif::LogicEquivalenceCheckingOp op, OpAdaptor adaptor,
148 ConversionPatternRewriter &rewriter) const override {
149 Location loc = op.getLoc();
150 auto *firstOutputs = adaptor.getFirstCircuit().front().getTerminator();
151 auto *secondOutputs = adaptor.getSecondCircuit().front().getTerminator();
152
153 auto hasNoResult = op.getNumResults() == 0;
154
155 if (firstOutputs->getNumOperands() == 0) {
156 // Trivially equivalent
157 if (hasNoResult) {
158 rewriter.eraseOp(op);
159 } else {
160 Value trueVal = arith::ConstantOp::create(rewriter, loc,
161 rewriter.getBoolAttr(true));
162 rewriter.replaceOp(op, trueVal);
163 }
164 return success();
165 }
166
167 // Solver will only return a result when it is used to check the returned
168 // value.
169 smt::SolverOp solver;
170 if (hasNoResult)
171 solver = smt::SolverOp::create(rewriter, loc, TypeRange{}, ValueRange{});
172 else
173 solver = smt::SolverOp::create(rewriter, loc, rewriter.getI1Type(),
174 ValueRange{});
175 rewriter.createBlock(&solver.getBodyRegion());
176
177 // First, convert the block arguments of the miter bodies.
178 if (failed(rewriter.convertRegionTypes(&adaptor.getFirstCircuit(),
179 *typeConverter)))
180 return failure();
181 if (failed(rewriter.convertRegionTypes(&adaptor.getSecondCircuit(),
182 *typeConverter)))
183 return failure();
184
185 // Second, create the symbolic values we replace the block arguments with
186 SmallVector<Value> inputs;
187 for (auto arg : adaptor.getFirstCircuit().getArguments())
188 inputs.push_back(smt::DeclareFunOp::create(rewriter, loc, arg.getType()));
189
190 // Third, inline the blocks
191 // Note: the argument value replacement does not happen immediately, but
192 // only after all the operations are already legalized.
193 // Also, it has to be ensured that the original argument type and the type
194 // of the value with which is is to be replaced match. The value is looked
195 // up (transitively) in the replacement map at the time the replacement
196 // pattern is committed.
197 rewriter.mergeBlocks(&adaptor.getFirstCircuit().front(), solver.getBody(),
198 inputs);
199 rewriter.mergeBlocks(&adaptor.getSecondCircuit().front(), solver.getBody(),
200 inputs);
201 rewriter.setInsertionPointToEnd(solver.getBody());
202
203 // Fourth, build the assertion.
204 SmallVector<Value> outputsDifferent;
205 createOutputsDifferentOps(firstOutputs, secondOutputs, loc, rewriter,
206 outputsDifferent);
207
208 rewriter.eraseOp(firstOutputs);
209 rewriter.eraseOp(secondOutputs);
210
211 Value toAssert;
212 if (outputsDifferent.size() == 1)
213 toAssert = outputsDifferent[0];
214 else
215 toAssert = smt::OrOp::create(rewriter, loc, outputsDifferent);
216
217 smt::AssertOp::create(rewriter, loc, toAssert);
218
219 // Fifth, check for satisfiablility and report the result back.
220 replaceOpWithSatCheck(op, loc, rewriter, solver);
221 return success();
222 }
223};
224
225struct RefinementCheckingOpConversion
226 : CircuitRelationCheckOpConversion<verif::RefinementCheckingOp> {
227 using CircuitRelationCheckOpConversion<
228 verif::RefinementCheckingOp>::CircuitRelationCheckOpConversion;
229
230 LogicalResult
231 matchAndRewrite(verif::RefinementCheckingOp op, OpAdaptor adaptor,
232 ConversionPatternRewriter &rewriter) const override {
233
234 // Find non-deterministic values (free variables) in the source circuit.
235 // For now, only support quantification over 'primitive' types.
236 SmallVector<Value> srcNonDetValues;
237 bool canBind = true;
238 for (auto ndOp : op.getFirstCircuit().getOps<smt::DeclareFunOp>()) {
239 if (!isa<smt::IntType, smt::BoolType, smt::BitVectorType>(
240 ndOp.getType())) {
241 ndOp.emitError("Uninterpreted function of non-primitive type cannot be "
242 "converted.");
243 canBind = false;
244 }
245 srcNonDetValues.push_back(ndOp.getResult());
246 }
247 if (!canBind)
248 return failure();
249
250 if (srcNonDetValues.empty()) {
251 // If there is no non-determinism in the source circuit, the
252 // refinement check becomes an equivalence check, which does not
253 // need quantified expressions.
254 auto eqOp = verif::LogicEquivalenceCheckingOp::create(
255 rewriter, op.getLoc(), op.getNumResults() != 0);
256 rewriter.moveBlockBefore(&op.getFirstCircuit().front(),
257 &eqOp.getFirstCircuit(),
258 eqOp.getFirstCircuit().end());
259 rewriter.moveBlockBefore(&op.getSecondCircuit().front(),
260 &eqOp.getSecondCircuit(),
261 eqOp.getSecondCircuit().end());
262 rewriter.replaceOp(op, eqOp);
263 return success();
264 }
265
266 Location loc = op.getLoc();
267 auto *firstOutputs = adaptor.getFirstCircuit().front().getTerminator();
268 auto *secondOutputs = adaptor.getSecondCircuit().front().getTerminator();
269
270 auto hasNoResult = op.getNumResults() == 0;
271
272 if (firstOutputs->getNumOperands() == 0) {
273 // Trivially equivalent
274 if (hasNoResult) {
275 rewriter.eraseOp(op);
276 } else {
277 Value trueVal = arith::ConstantOp::create(rewriter, loc,
278 rewriter.getBoolAttr(true));
279 rewriter.replaceOp(op, trueVal);
280 }
281 return success();
282 }
283
284 // Solver will only return a result when it is used to check the returned
285 // value.
286 smt::SolverOp solver;
287 if (hasNoResult)
288 solver = smt::SolverOp::create(rewriter, loc, TypeRange{}, ValueRange{});
289 else
290 solver = smt::SolverOp::create(rewriter, loc, rewriter.getI1Type(),
291 ValueRange{});
292 rewriter.createBlock(&solver.getBodyRegion());
293
294 // Convert the block arguments of the miter bodies.
295 if (failed(rewriter.convertRegionTypes(&adaptor.getFirstCircuit(),
296 *typeConverter)))
297 return failure();
298 if (failed(rewriter.convertRegionTypes(&adaptor.getSecondCircuit(),
299 *typeConverter)))
300 return failure();
301
302 // Create the symbolic values we replace the block arguments with
303 SmallVector<Value> inputs;
304 for (auto arg : adaptor.getFirstCircuit().getArguments())
305 inputs.push_back(smt::DeclareFunOp::create(rewriter, loc, arg.getType()));
306
307 // Inline the target circuit. Free variables remain free variables.
308 rewriter.mergeBlocks(&adaptor.getSecondCircuit().front(), solver.getBody(),
309 inputs);
310 rewriter.setInsertionPointToEnd(solver.getBody());
311
312 // Create the universally quantified expression containing the source
313 // circuit. Free variables in the circuit's body become bound variables.
314 auto forallOp = smt::ForallOp::create(
315 rewriter, op.getLoc(), TypeRange(srcNonDetValues),
316 [&](OpBuilder &builder, auto, ValueRange args) -> Value {
317 // Inline the source circuit
318 Block *body = builder.getBlock();
319 rewriter.mergeBlocks(&adaptor.getFirstCircuit().front(), body,
320 inputs);
321
322 // Replace non-deterministic values with the quantifier's bound
323 // variables
324 for (auto [freeVar, boundVar] : llvm::zip(srcNonDetValues, args))
325 rewriter.replaceOp(freeVar.getDefiningOp(), boundVar);
326
327 // Compare the output values
328 rewriter.setInsertionPointToEnd(body);
329 SmallVector<Value> outputsDifferent;
330 createOutputsDifferentOps(firstOutputs, secondOutputs, loc, rewriter,
331 outputsDifferent);
332 if (outputsDifferent.size() == 1)
333 return outputsDifferent[0];
334 else
335 return rewriter.createOrFold<smt::OrOp>(loc, outputsDifferent);
336 });
337
338 rewriter.eraseOp(firstOutputs);
339 rewriter.eraseOp(secondOutputs);
340
341 // Assert the quantified expression
342 rewriter.setInsertionPointAfter(forallOp);
343 smt::AssertOp::create(rewriter, op.getLoc(), forallOp.getResult());
344
345 // Check for satisfiability and report the result back.
346 replaceOpWithSatCheck(op, loc, rewriter, solver);
347 return success();
348 }
349};
350
351/// Lower a verif::BMCOp operation to an MLIR program that performs the bounded
352/// model check
353struct VerifBoundedModelCheckingOpConversion
354 : OpConversionPattern<verif::BoundedModelCheckingOp> {
355 using OpConversionPattern<verif::BoundedModelCheckingOp>::OpConversionPattern;
356
357 VerifBoundedModelCheckingOpConversion(TypeConverter &converter,
358 MLIRContext *context, Namespace &names,
359 bool risingClocksOnly)
360 : OpConversionPattern(converter, context), names(names),
361 risingClocksOnly(risingClocksOnly) {}
362 LogicalResult
363 matchAndRewrite(verif::BoundedModelCheckingOp op, OpAdaptor adaptor,
364 ConversionPatternRewriter &rewriter) const override {
365 Location loc = op.getLoc();
366 SmallVector<Type> oldLoopInputTy(op.getLoop().getArgumentTypes());
367 SmallVector<Type> oldCircuitInputTy(op.getCircuit().getArgumentTypes());
368 // TODO: the init and loop regions should be able to be concrete instead of
369 // symbolic which is probably preferable - just need to convert back and
370 // forth
371 SmallVector<Type> loopInputTy, circuitInputTy, initOutputTy,
372 circuitOutputTy;
373 if (failed(typeConverter->convertTypes(oldLoopInputTy, loopInputTy)))
374 return failure();
375 if (failed(typeConverter->convertTypes(oldCircuitInputTy, circuitInputTy)))
376 return failure();
377 if (failed(typeConverter->convertTypes(
378 op.getInit().front().back().getOperandTypes(), initOutputTy)))
379 return failure();
380 if (failed(typeConverter->convertTypes(
381 op.getCircuit().front().back().getOperandTypes(), circuitOutputTy)))
382 return failure();
383 if (failed(rewriter.convertRegionTypes(&op.getInit(), *typeConverter)))
384 return failure();
385 if (failed(rewriter.convertRegionTypes(&op.getLoop(), *typeConverter)))
386 return failure();
387 if (failed(rewriter.convertRegionTypes(&op.getCircuit(), *typeConverter)))
388 return failure();
389
390 unsigned numRegs = op.getNumRegs();
391 auto initialValues = op.getInitialValues();
392
393 auto initFuncTy = rewriter.getFunctionType({}, initOutputTy);
394 // Loop and init output types are necessarily the same, so just use init
395 // output types
396 auto loopFuncTy = rewriter.getFunctionType(loopInputTy, initOutputTy);
397 auto circuitFuncTy =
398 rewriter.getFunctionType(circuitInputTy, circuitOutputTy);
399
400 func::FuncOp initFuncOp, loopFuncOp, circuitFuncOp;
401
402 {
403 OpBuilder::InsertionGuard guard(rewriter);
404 rewriter.setInsertionPointToEnd(
405 op->getParentOfType<ModuleOp>().getBody());
406 initFuncOp = func::FuncOp::create(rewriter, loc,
407 names.newName("bmc_init"), initFuncTy);
408 rewriter.inlineRegionBefore(op.getInit(), initFuncOp.getFunctionBody(),
409 initFuncOp.end());
410 loopFuncOp = func::FuncOp::create(rewriter, loc,
411 names.newName("bmc_loop"), loopFuncTy);
412 rewriter.inlineRegionBefore(op.getLoop(), loopFuncOp.getFunctionBody(),
413 loopFuncOp.end());
414 circuitFuncOp = func::FuncOp::create(
415 rewriter, loc, names.newName("bmc_circuit"), circuitFuncTy);
416 rewriter.inlineRegionBefore(op.getCircuit(),
417 circuitFuncOp.getFunctionBody(),
418 circuitFuncOp.end());
419 auto funcOps = {&initFuncOp, &loopFuncOp, &circuitFuncOp};
420 // initOutputTy is the same as loop output types
421 auto outputTys = {initOutputTy, initOutputTy, circuitOutputTy};
422 for (auto [funcOp, outputTy] : llvm::zip(funcOps, outputTys)) {
423 auto operands = funcOp->getBody().front().back().getOperands();
424 rewriter.eraseOp(&funcOp->getFunctionBody().front().back());
425 rewriter.setInsertionPointToEnd(&funcOp->getBody().front());
426 SmallVector<Value> toReturn;
427 for (unsigned i = 0; i < outputTy.size(); ++i)
428 toReturn.push_back(typeConverter->materializeTargetConversion(
429 rewriter, loc, outputTy[i], operands[i]));
430 func::ReturnOp::create(rewriter, loc, toReturn);
431 }
432 }
433
434 auto solver = smt::SolverOp::create(rewriter, loc, rewriter.getI1Type(),
435 ValueRange{});
436 rewriter.createBlock(&solver.getBodyRegion());
437
438 // Call init func to get initial clock values
439 ValueRange initVals =
440 func::CallOp::create(rewriter, loc, initFuncOp)->getResults();
441
442 // Initial push
443 smt::PushOp::create(rewriter, loc, 1);
444
445 // InputDecls order should be <circuit arguments> <state arguments>
446 // <wasViolated>
447 // Get list of clock indexes in circuit args
448 size_t initIndex = 0;
449 SmallVector<Value> inputDecls;
450 SmallVector<int> clockIndexes;
451 for (auto [curIndex, oldTy, newTy] :
452 llvm::enumerate(oldCircuitInputTy, circuitInputTy)) {
453 if (isa<seq::ClockType>(oldTy)) {
454 inputDecls.push_back(initVals[initIndex++]);
455 clockIndexes.push_back(curIndex);
456 continue;
457 }
458 if (curIndex >= oldCircuitInputTy.size() - numRegs) {
459 auto initVal =
460 initialValues[curIndex - oldCircuitInputTy.size() + numRegs];
461 if (auto initIntAttr = dyn_cast<IntegerAttr>(initVal)) {
462 const auto &cstInt = initIntAttr.getValue();
463 assert(cstInt.getBitWidth() ==
464 cast<smt::BitVectorType>(newTy).getWidth() &&
465 "Width mismatch between initial value and target type");
466 inputDecls.push_back(
467 smt::BVConstantOp::create(rewriter, loc, cstInt));
468 continue;
469 }
470 }
471 inputDecls.push_back(smt::DeclareFunOp::create(rewriter, loc, newTy));
472 }
473
474 auto numStateArgs = initVals.size() - initIndex;
475 // Add the rest of the init vals (state args)
476 for (; initIndex < initVals.size(); ++initIndex)
477 inputDecls.push_back(initVals[initIndex]);
478
479 Value lowerBound =
480 arith::ConstantOp::create(rewriter, loc, rewriter.getI32IntegerAttr(0));
481 Value step =
482 arith::ConstantOp::create(rewriter, loc, rewriter.getI32IntegerAttr(1));
483 Value upperBound =
484 arith::ConstantOp::create(rewriter, loc, adaptor.getBoundAttr());
485 Value constFalse =
486 arith::ConstantOp::create(rewriter, loc, rewriter.getBoolAttr(false));
487 Value constTrue =
488 arith::ConstantOp::create(rewriter, loc, rewriter.getBoolAttr(true));
489 inputDecls.push_back(constFalse); // wasViolated?
490
491 // TODO: swapping to a whileOp here would allow early exit once the property
492 // is violated
493 // Perform model check up to the provided bound
494 auto forOp = scf::ForOp::create(
495 rewriter, loc, lowerBound, upperBound, step, inputDecls,
496 [&](OpBuilder &builder, Location loc, Value i, ValueRange iterArgs) {
497 // Drop existing assertions
498 smt::PopOp::create(builder, loc, 1);
499 smt::PushOp::create(builder, loc, 1);
500
501 // Execute the circuit
502 ValueRange circuitCallOuts =
503 func::CallOp::create(
504 builder, loc, circuitFuncOp,
505 iterArgs.take_front(circuitFuncOp.getNumArguments()))
506 ->getResults();
507
508 // If we have a cycle up to which we ignore assertions, we need an
509 // IfOp to track this
510 // First, save the insertion point so we can safely enter the IfOp
511
512 auto insideForPoint = builder.saveInsertionPoint();
513 // We need to still have the yielded result of the op in scope after
514 // we've built the check
515 Value yieldedValue;
516 auto ignoreAssertionsUntil =
517 op->getAttrOfType<IntegerAttr>("ignore_asserts_until");
518 if (ignoreAssertionsUntil) {
519 auto ignoreUntilConstant = arith::ConstantOp::create(
520 builder, loc,
521 rewriter.getI32IntegerAttr(
522 ignoreAssertionsUntil.getValue().getZExtValue()));
523 auto shouldIgnore =
524 arith::CmpIOp::create(builder, loc, arith::CmpIPredicate::ult,
525 i, ignoreUntilConstant);
526 auto ifShouldIgnore = scf::IfOp::create(
527 builder, loc, builder.getI1Type(), shouldIgnore, true);
528 // If we should ignore, yield the existing value
529 builder.setInsertionPointToEnd(
530 &ifShouldIgnore.getThenRegion().front());
531 scf::YieldOp::create(builder, loc, ValueRange(iterArgs.back()));
532 builder.setInsertionPointToEnd(
533 &ifShouldIgnore.getElseRegion().front());
534 yieldedValue = ifShouldIgnore.getResult(0);
535 }
536
537 auto checkOp =
538 smt::CheckOp::create(rewriter, loc, builder.getI1Type());
539 {
540 OpBuilder::InsertionGuard guard(builder);
541 builder.createBlock(&checkOp.getSatRegion());
542 smt::YieldOp::create(builder, loc, constTrue);
543 builder.createBlock(&checkOp.getUnknownRegion());
544 smt::YieldOp::create(builder, loc, constTrue);
545 builder.createBlock(&checkOp.getUnsatRegion());
546 smt::YieldOp::create(builder, loc, constFalse);
547 }
548
549 Value violated = arith::OrIOp::create(
550 builder, loc, checkOp.getResult(0), iterArgs.back());
551
552 // If we've packaged everything in an IfOp, we need to yield the
553 // new violated value
554 if (ignoreAssertionsUntil) {
555 scf::YieldOp::create(builder, loc, violated);
556 // Replace the variable with the yielded value
557 violated = yieldedValue;
558 }
559
560 // If we created an IfOp, make sure we start inserting after it again
561 builder.restoreInsertionPoint(insideForPoint);
562
563 // Call loop func to update clock & state arg values
564 SmallVector<Value> loopCallInputs;
565 // Fetch clock values to feed to loop
566 for (auto index : clockIndexes)
567 loopCallInputs.push_back(iterArgs[index]);
568 // Fetch state args to feed to loop
569 for (auto stateArg : iterArgs.drop_back().take_back(numStateArgs))
570 loopCallInputs.push_back(stateArg);
571 ValueRange loopVals =
572 func::CallOp::create(builder, loc, loopFuncOp, loopCallInputs)
573 ->getResults();
574
575 size_t loopIndex = 0;
576 // Collect decls to yield at end of iteration
577 SmallVector<Value> newDecls;
578 for (auto [oldTy, newTy] :
579 llvm::zip(TypeRange(oldCircuitInputTy).drop_back(numRegs),
580 TypeRange(circuitInputTy).drop_back(numRegs))) {
581 if (isa<seq::ClockType>(oldTy))
582 newDecls.push_back(loopVals[loopIndex++]);
583 else
584 newDecls.push_back(
585 smt::DeclareFunOp::create(builder, loc, newTy));
586 }
587
588 // Only update the registers on a clock posedge unless in rising
589 // clocks only mode
590 // TODO: this will also need changing with multiple clocks - currently
591 // it only accounts for the one clock case.
592 if (clockIndexes.size() == 1) {
593 SmallVector<Value> regInputs = circuitCallOuts.take_back(numRegs);
594 if (risingClocksOnly) {
595 // In rising clocks only mode we don't need to worry about whether
596 // there was a posedge
597 newDecls.append(regInputs);
598 } else {
599 auto clockIndex = clockIndexes[0];
600 auto oldClock = iterArgs[clockIndex];
601 // The clock is necessarily the first value returned by the loop
602 // region
603 auto newClock = loopVals[0];
604 auto oldClockLow = smt::BVNotOp::create(builder, loc, oldClock);
605 auto isPosedgeBV =
606 smt::BVAndOp::create(builder, loc, oldClockLow, newClock);
607 // Convert posedge bv<1> to bool
608 auto trueBV = smt::BVConstantOp::create(builder, loc, 1, 1);
609 auto isPosedge =
610 smt::EqOp::create(builder, loc, isPosedgeBV, trueBV);
611 auto regStates =
612 iterArgs.take_front(circuitFuncOp.getNumArguments())
613 .take_back(numRegs);
614 SmallVector<Value> nextRegStates;
615 for (auto [regState, regInput] :
616 llvm::zip(regStates, regInputs)) {
617 // Create an ITE to calculate the next reg state
618 // TODO: we create a lot of ITEs here that will slow things down
619 // - these could be avoided by making init/loop regions concrete
620 nextRegStates.push_back(smt::IteOp::create(
621 builder, loc, isPosedge, regInput, regState));
622 }
623 newDecls.append(nextRegStates);
624 }
625 }
626
627 // Add the rest of the loop state args
628 for (; loopIndex < loopVals.size(); ++loopIndex)
629 newDecls.push_back(loopVals[loopIndex]);
630
631 newDecls.push_back(violated);
632
633 scf::YieldOp::create(builder, loc, newDecls);
634 });
635
636 Value res = arith::XOrIOp::create(rewriter, loc, forOp->getResults().back(),
637 constTrue);
638 smt::YieldOp::create(rewriter, loc, res);
639 rewriter.replaceOp(op, solver.getResults());
640 return success();
641 }
642
643 Namespace &names;
644 bool risingClocksOnly;
645};
646
647} // namespace
648
649//===----------------------------------------------------------------------===//
650// Convert Verif to SMT pass
651//===----------------------------------------------------------------------===//
652
653namespace {
654struct ConvertVerifToSMTPass
655 : public circt::impl::ConvertVerifToSMTBase<ConvertVerifToSMTPass> {
656 using Base::Base;
657 void runOnOperation() override;
658};
659} // namespace
660
662 RewritePatternSet &patterns,
663 Namespace &names,
664 bool risingClocksOnly) {
665 patterns.add<VerifAssertOpConversion, VerifAssumeOpConversion,
666 LogicEquivalenceCheckingOpConversion,
667 RefinementCheckingOpConversion>(converter,
668 patterns.getContext());
669 patterns.add<VerifBoundedModelCheckingOpConversion>(
670 converter, patterns.getContext(), names, risingClocksOnly);
671}
672
673void ConvertVerifToSMTPass::runOnOperation() {
674 ConversionTarget target(getContext());
675 target.addIllegalDialect<verif::VerifDialect>();
676 target.addLegalDialect<smt::SMTDialect, arith::ArithDialect, scf::SCFDialect,
677 func::FuncDialect>();
678 target.addLegalOp<UnrealizedConversionCastOp>();
679
680 // Check BMC ops contain only one assertion (done outside pattern to avoid
681 // issues with whether assertions are/aren't lowered yet)
682 SymbolTable symbolTable(getOperation());
683 WalkResult assertionCheck = getOperation().walk(
684 [&](Operation *op) { // Check there is exactly one assertion and clock
685 if (auto bmcOp = dyn_cast<verif::BoundedModelCheckingOp>(op)) {
686 // We also currently don't support initial values on registers that
687 // don't have integer inputs.
688 auto regTypes = TypeRange(bmcOp.getCircuit().getArgumentTypes())
689 .take_back(bmcOp.getNumRegs());
690 for (auto [regType, initVal] :
691 llvm::zip(regTypes, bmcOp.getInitialValues())) {
692 if (!isa<UnitAttr>(initVal)) {
693 if (!isa<IntegerType>(regType)) {
694 op->emitError("initial values are currently only supported for "
695 "registers with integer types");
696 signalPassFailure();
697 return WalkResult::interrupt();
698 } else {
699 auto tyAttr = dyn_cast<TypedAttr>(initVal);
700 if (!tyAttr || tyAttr.getType() != regType) {
701 op->emitError("type of initial value does not match type of "
702 "initialized register");
703 signalPassFailure();
704 return WalkResult::interrupt();
705 }
706 }
707 }
708 }
709 // Check only one clock is present in the circuit inputs
710 auto numClockArgs = 0;
711 for (auto argType : bmcOp.getCircuit().getArgumentTypes())
712 if (isa<seq::ClockType>(argType))
713 numClockArgs++;
714 // TODO: this can be removed once we have a way to associate reg
715 // ins/outs with clocks
716 if (numClockArgs > 1) {
717 op->emitError(
718 "only modules with one or zero clocks are currently supported");
719 return WalkResult::interrupt();
720 }
721 SmallVector<mlir::Operation *> worklist;
722 int numAssertions = 0;
723 op->walk([&](Operation *curOp) {
724 if (isa<verif::AssertOp>(curOp))
725 numAssertions++;
726 if (auto inst = dyn_cast<InstanceOp>(curOp))
727 worklist.push_back(symbolTable.lookup(inst.getModuleName()));
728 });
729 // TODO: probably negligible compared to actual model checking time
730 // but cacheing the assertion count of modules would speed this up
731 while (!worklist.empty()) {
732 auto *module = worklist.pop_back_val();
733 module->walk([&](Operation *curOp) {
734 if (isa<verif::AssertOp>(curOp))
735 numAssertions++;
736 if (auto inst = dyn_cast<InstanceOp>(curOp))
737 worklist.push_back(symbolTable.lookup(inst.getModuleName()));
738 });
739 if (numAssertions > 1)
740 break;
741 }
742 if (numAssertions > 1) {
743 op->emitError(
744 "bounded model checking problems with multiple assertions are "
745 "not yet "
746 "correctly handled - instead, you can assert the "
747 "conjunction of your assertions");
748 return WalkResult::interrupt();
749 }
750 }
751 return WalkResult::advance();
752 });
753 if (assertionCheck.wasInterrupted())
754 return signalPassFailure();
755 RewritePatternSet patterns(&getContext());
756 TypeConverter converter;
758
759 SymbolCache symCache;
760 symCache.addDefinitions(getOperation());
761 Namespace names;
762 names.add(symCache);
763
765 risingClocksOnly);
766
767 if (failed(mlir::applyPartialConversion(getOperation(), target,
768 std::move(patterns))))
769 return signalPassFailure();
770}
assert(baseType &&"element must be base type")
A namespace that is used to store existing names and generate new names in some scope within the IR.
Definition Namespace.h:30
void add(mlir::ModuleOp module)
Definition Namespace.h:48
void addDefinitions(mlir::Operation *top)
Populate the symbol cache with all symbol-defining operations within the 'top' operation.
Definition SymCache.cpp:23
Default symbol cache implementation; stores associations between names (StringAttr's) to mlir::Operat...
Definition SymCache.h:85
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
void populateVerifToSMTConversionPatterns(TypeConverter &converter, RewritePatternSet &patterns, Namespace &names, bool risingClocksOnly)
Get the Verif to SMT conversion patterns.
void populateHWToSMTTypeConverter(TypeConverter &converter)
Get the HW to SMT type conversions.
Definition HWToSMT.cpp:218
Definition hw.py:1
Definition seq.py:1