18 #include "mlir/Dialect/Func/IR/FuncOps.h"
19 #include "mlir/IR/BuiltinOps.h"
20 #include "mlir/Support/IndentedOstream.h"
21 #include "mlir/Tools/mlir-translate/Translation.h"
22 #include "llvm/ADT/ScopedHashTable.h"
23 #include "llvm/Support/Format.h"
25 using namespace circt;
27 using namespace ExportSMTLIB;
29 using ValueMap = llvm::ScopedHashTable<mlir::Value, std::string>;
31 #define DEBUG_TYPE "export-smtlib"
39 mlir::raw_indented_ostream &> {
42 void visitSMTType(BoolType type, mlir::raw_indented_ostream &stream) {
46 void visitSMTType(IntType type, mlir::raw_indented_ostream &stream) {
50 void visitSMTType(BitVectorType type, mlir::raw_indented_ostream &stream) {
51 stream <<
"(_ BitVec " << type.getWidth() <<
")";
54 void visitSMTType(ArrayType type, mlir::raw_indented_ostream &stream) {
56 dispatchSMTTypeVisitor(type.getDomainType(), stream);
58 dispatchSMTTypeVisitor(type.getRangeType(), stream);
62 void visitSMTType(SMTFuncType type, mlir::raw_indented_ostream &stream) {
64 StringLiteral nextToken =
"";
66 for (Type domainTy : type.getDomainTypes()) {
68 dispatchSMTTypeVisitor(domainTy, stream);
73 dispatchSMTTypeVisitor(type.getRangeType(), stream);
76 void visitSMTType(SortType type, mlir::raw_indented_ostream &stream) {
77 if (!type.getSortParams().empty())
80 stream << type.getIdentifier().getValue();
81 for (Type paramTy : type.getSortParams()) {
83 dispatchSMTTypeVisitor(paramTy, stream);
86 if (!type.getSortParams().empty())
98 VisitorInfo(mlir::raw_indented_ostream &stream,
ValueMap &valueMap)
99 : stream(stream), valueMap(valueMap) {}
100 VisitorInfo(mlir::raw_indented_ostream &stream,
ValueMap &valueMap,
101 unsigned indentLevel,
unsigned openParens)
102 : stream(stream), valueMap(valueMap), indentLevel(indentLevel),
103 openParens(openParens) {}
106 mlir::raw_indented_ostream &stream;
110 unsigned indentLevel = 0;
112 unsigned openParens = 0;
117 struct ExpressionVisitor
122 using Base::visitSMTOp;
125 : options(options), typeVisitor(options), names(names) {}
127 LogicalResult dispatchSMTOpVisitor(Operation *op, VisitorInfo &info) {
128 assert(op->getNumResults() == 1 &&
129 "expression op must have exactly one result value");
138 Value res = op->getResult(0);
141 llvm::raw_string_ostream sstream(str);
142 mlir::raw_indented_ostream indentedStream(sstream);
144 VisitorInfo newInfo(indentedStream, info.valueMap, info.indentLevel,
146 if (failed(Base::dispatchSMTOpVisitor(op, newInfo)))
149 info.valueMap.insert(res, str);
156 auto name = names.
newName(
"tmp");
157 info.valueMap.insert(res, name.str());
158 info.stream <<
"(let ((" << name <<
" ";
160 VisitorInfo newInfo(info.stream, info.valueMap,
161 info.indentLevel + 8 + name.size(), 0);
162 if (failed(Base::dispatchSMTOpVisitor(op, newInfo)))
165 info.stream <<
"))\n";
169 info.indentLevel += 5;
172 info.stream.indent(info.indentLevel);
181 template <
typename Op>
182 LogicalResult printBinaryOp(Op op, StringRef name, VisitorInfo &info) {
183 info.stream <<
"(" << name <<
" " << info.valueMap.lookup(op.getLhs())
184 <<
" " << info.valueMap.lookup(op.getRhs()) <<
")";
188 template <
typename Op>
189 LogicalResult printVariadicOp(Op op, StringRef name, VisitorInfo &info) {
190 info.stream <<
"(" << name;
191 for (Value val : op.getOperands())
192 info.stream <<
" " << info.valueMap.lookup(val);
197 LogicalResult visitSMTOp(BVNegOp op, VisitorInfo &info) {
198 info.stream <<
"(bvneg " << info.valueMap.lookup(op.getInput()) <<
")";
202 LogicalResult visitSMTOp(BVNotOp op, VisitorInfo &info) {
203 info.stream <<
"(bvnot " << info.valueMap.lookup(op.getInput()) <<
")";
207 #define HANDLE_OP(OPTYPE, NAME, KIND) \
208 LogicalResult visitSMTOp(OPTYPE op, VisitorInfo &info) { \
209 return print##KIND##Op(op, NAME, info); \
227 LogicalResult visitSMTOp(ExtractOp op, VisitorInfo &info) {
228 info.stream <<
"((_ extract "
229 << (op.getLowBit() + op.getType().getWidth() - 1) <<
" "
230 << op.getLowBit() <<
") " << info.valueMap.lookup(op.getInput())
235 LogicalResult visitSMTOp(RepeatOp op, VisitorInfo &info) {
236 info.stream <<
"((_ repeat " << op.getCount() <<
") "
237 << info.valueMap.lookup(op.getInput()) <<
")";
241 LogicalResult visitSMTOp(BVCmpOp op, VisitorInfo &info) {
242 return printBinaryOp(op,
"bv" + stringifyBVCmpPredicate(op.getPred()).str(),
256 LogicalResult visitSMTOp(IntCmpOp op, VisitorInfo &info) {
257 switch (op.getPred()) {
258 case IntPredicate::ge:
259 return printBinaryOp(op,
">=", info);
260 case IntPredicate::le:
261 return printBinaryOp(op,
"<=", info);
262 case IntPredicate::gt:
263 return printBinaryOp(op,
">", info);
264 case IntPredicate::lt:
265 return printBinaryOp(op,
"<", info);
275 HANDLE_OP(DistinctOp,
"distinct", Variadic);
277 LogicalResult visitSMTOp(IteOp op, VisitorInfo &info) {
278 info.stream <<
"(ite " << info.valueMap.lookup(op.getCond()) <<
" "
279 << info.valueMap.lookup(op.getThenValue()) <<
" "
280 << info.valueMap.lookup(op.getElseValue()) <<
")";
284 LogicalResult visitSMTOp(ApplyFuncOp op, VisitorInfo &info) {
285 info.stream <<
"(" << info.valueMap.lookup(op.getFunc());
286 for (Value arg : op.getArgs())
287 info.stream <<
" " << info.valueMap.lookup(arg);
292 template <
typename OpTy>
293 LogicalResult quantifierHelper(OpTy op, StringRef operatorString,
295 auto weight = op.getWeight();
297 if (op.getNoPattern())
298 return op.emitError() <<
"no-pattern attribute not supported yet";
299 if (!op.getPatterns().empty())
300 return op.emitError() <<
"patterns not supported yet";
302 llvm::ScopedHashTableScope<Value, std::string> scope(info.valueMap);
303 info.stream <<
"(" << operatorString <<
" (";
305 StringLiteral delimiter =
"";
306 for (
auto [i, arg] : llvm::enumerate(op.getBody().getArguments())) {
309 op.getBoundVarNames()
310 ? cast<StringAttr>(op.getBoundVarNames()->getValue()[i])
313 StringRef name = names.
newName(prefix);
314 info.valueMap.insert(arg, name.str());
317 info.stream << delimiter <<
"(" << name <<
" ";
318 typeVisitor.dispatchSMTTypeVisitor(arg.getType(), info.stream);
323 info.stream <<
")\n";
326 info.stream <<
"( ! ";
330 SmallVector<Value> worklist;
331 Value yieldedValue = op.getBody().front().getTerminator()->getOperand(0);
332 worklist.push_back(yieldedValue);
333 unsigned indentExt = operatorString.size() + 2;
334 VisitorInfo newInfo(info.stream, info.valueMap,
335 info.indentLevel + indentExt, 0);
336 newInfo.stream.indent(newInfo.indentLevel);
337 if (failed(printExpression(worklist, newInfo)))
340 info.stream << info.valueMap.lookup(yieldedValue);
342 for (
unsigned j = 0; j < newInfo.openParens; ++j)
346 info.stream <<
" :weight " << weight <<
")";
353 LogicalResult visitSMTOp(ForallOp op, VisitorInfo &info) {
354 return quantifierHelper(op,
"forall", info);
357 LogicalResult visitSMTOp(ExistsOp op, VisitorInfo &info) {
358 return quantifierHelper(op,
"exists", info);
361 LogicalResult visitSMTOp(NotOp op, VisitorInfo &info) {
362 info.stream <<
"(not " << info.valueMap.lookup(op.getInput()) <<
")";
375 LogicalResult visitSMTOp(ArrayStoreOp op, VisitorInfo &info) {
376 info.stream <<
"(store " << info.valueMap.lookup(op.getArray()) <<
" "
377 << info.valueMap.lookup(op.getIndex()) <<
" "
378 << info.valueMap.lookup(op.getValue()) <<
")";
382 LogicalResult visitSMTOp(ArraySelectOp op, VisitorInfo &info) {
383 info.stream <<
"(select " << info.valueMap.lookup(op.getArray()) <<
" "
384 << info.valueMap.lookup(op.getIndex()) <<
")";
388 LogicalResult visitSMTOp(ArrayBroadcastOp op, VisitorInfo &info) {
389 info.stream <<
"((as const ";
390 typeVisitor.dispatchSMTTypeVisitor(op.getType(), info.stream);
391 info.stream <<
") " << info.valueMap.lookup(op.getValue()) <<
")";
395 LogicalResult visitUnhandledSMTOp(Operation *op, VisitorInfo &info) {
403 LogicalResult printExpression(SmallVector<Value> &worklist,
405 while (!worklist.empty()) {
406 Value curr = worklist.back();
409 if (info.valueMap.count(curr)) {
416 bool allAvailable =
true;
417 Operation *defOp = curr.getDefiningOp();
418 assert(defOp !=
nullptr &&
419 "block arguments must already be in the valueMap");
421 for (Value val : defOp->getOperands()) {
422 if (!info.valueMap.count(val)) {
423 worklist.push_back(val);
424 allAvailable =
false;
431 if (failed(dispatchSMTOpVisitor(curr.getDefiningOp(), info)))
443 TypeVisitor typeVisitor;
449 struct StatementVisitor
451 mlir::raw_indented_ostream &, ValueMap &> {
453 mlir::raw_indented_ostream &,
ValueMap &>::visitSMTOp;
456 : options(options), typeVisitor(options), names(names),
457 exprVisitor(options, names) {}
459 LogicalResult visitSMTOp(BVConstantOp op, mlir::raw_indented_ostream &stream,
461 valueMap.insert(op.getResult(), op.getValue().getValueAsString());
465 LogicalResult visitSMTOp(BoolConstantOp op,
466 mlir::raw_indented_ostream &stream,
468 valueMap.insert(op.getResult(), op.getValue() ?
"true" :
"false");
472 LogicalResult visitSMTOp(IntConstantOp op, mlir::raw_indented_ostream &stream,
475 op.getValue().toStringSigned(str);
476 valueMap.insert(op.getResult(), str.str().str());
480 LogicalResult visitSMTOp(DeclareFunOp op, mlir::raw_indented_ostream &stream,
483 names.
newName(op.getNamePrefix() ? *op.getNamePrefix() :
"tmp");
484 valueMap.insert(op.getResult(), name.str());
486 << (isa<SMTFuncType>(op.getType()) ?
"declare-fun "
489 typeVisitor.dispatchSMTTypeVisitor(op.getType(), stream);
494 LogicalResult visitSMTOp(AssertOp op, mlir::raw_indented_ostream &stream,
496 llvm::ScopedHashTableScope<Value, std::string> scope1(valueMap);
497 SmallVector<Value> worklist;
498 worklist.push_back(op.getInput());
499 stream <<
"(assert ";
500 VisitorInfo info(stream, valueMap, 8, 0);
501 if (failed(exprVisitor.printExpression(worklist, info)))
503 stream << valueMap.lookup(op.getInput());
504 for (
unsigned i = 0; i < info.openParens + 1; ++i)
511 LogicalResult visitSMTOp(CheckOp op, mlir::raw_indented_ostream &stream,
513 if (op->getNumResults() != 0)
514 return op.emitError() <<
"must not have any result values";
516 if (op.getSatRegion().front().getOperations().size() != 1)
517 return op->emitError() <<
"'sat' region must be empty";
518 if (op.getUnknownRegion().front().getOperations().size() != 1)
519 return op->emitError() <<
"'unknown' region must be empty";
520 if (op.getUnsatRegion().front().getOperations().size() != 1)
521 return op->emitError() <<
"'unsat' region must be empty";
523 stream <<
"(check-sat)\n";
527 LogicalResult visitUnhandledSMTOp(Operation *op,
528 mlir::raw_indented_ostream &stream,
537 TypeVisitor typeVisitor;
539 ExpressionVisitor exprVisitor;
550 mlir::raw_indented_ostream &stream) {
551 if (!solver.getInputs().empty() || solver->getNumResults() != 0)
552 return solver->emitError()
553 <<
"solver scopes with inputs or results are not supported";
555 Block *block = solver.getBody();
558 DenseMap<StringAttr, unsigned> declaredSorts;
559 auto result = block->walk([&](Operation *op) -> WalkResult {
560 if (!isa<SMTDialect>(op->getDialect()))
561 return op->emitError()
562 <<
"solver must not contain any non-SMT operations";
564 for (Type resTy : op->getResultTypes()) {
565 auto sortTy = dyn_cast<SortType>(resTy);
569 unsigned arity = sortTy.getSortParams().size();
570 if (declaredSorts.contains(sortTy.getIdentifier())) {
571 if (declaredSorts[sortTy.getIdentifier()] != arity)
572 return op->emitError(
"uninterpreted sorts with same identifier but "
573 "different arity found");
578 declaredSorts[sortTy.getIdentifier()] = arity;
579 stream <<
"(declare-sort " << sortTy.getIdentifier().getValue() <<
" "
582 return WalkResult::advance();
584 if (result.wasInterrupted())
588 llvm::ScopedHashTableScope<Value, std::string> scope0(valueMap);
590 StatementVisitor visitor(options, names);
594 result = block->walk([&](Operation *op) {
595 if (failed(visitor.dispatchSMTOpVisitor(op, stream, valueMap)))
596 return WalkResult::interrupt();
597 return WalkResult::advance();
599 if (result.wasInterrupted())
602 stream <<
"(reset)\n";
607 llvm::raw_ostream &os,
609 if (module->getNumRegions() != 1)
610 return module->emitError(
"must have exactly one region");
611 if (!module->getRegion(0).hasOneBlock())
612 return module->emitError(
"op region must have exactly one block");
614 mlir::raw_indented_ostream ios(os);
615 unsigned solverIdx = 0;
616 auto result = module->walk([&](SolverOp solver) {
617 ios <<
"; solver scope " << solverIdx <<
"\n";
618 if (failed(
emit(solver, options, ios)))
619 return WalkResult::interrupt();
621 return WalkResult::advance();
624 return failure(result.wasInterrupted());
633 "smtlibexport-inline-single-use-values",
634 llvm::cl::desc(
"Inline expressions that are used only once rather than "
635 "generating a let-binding"),
636 llvm::cl::init(
false));
638 auto getOptions = [] {
644 static mlir::TranslateFromMLIRRegistration toSMTLIB(
645 "export-smtlib",
"export SMT-LIB",
646 [=](Operation *module, raw_ostream &output) {
649 [](mlir::DialectRegistry ®istry) {
653 .insert<mlir::func::FuncDialect, hw::HWDialect, smt::SMTDialect>();
assert(baseType &&"element must be base type")
static LogicalResult emit(SolverOp solver, const SMTEmissionOptions &options, mlir::raw_indented_ostream &stream)
Emit the SMT operations in the given 'solver' to the 'stream'.
#define HANDLE_OP(OPTYPE, NAME, KIND)
llvm::ScopedHashTable< mlir::Value, std::string > ValueMap
A namespace that is used to store existing names and generate new names in some scope within the IR.
StringRef newName(const Twine &name)
Return a unique name, derived from the input name, and add the new name to the internal namespace.
This helps visit SMT nodes.
This helps visit SMT types.
LogicalResult exportSMTLIB(Operation *module, llvm::raw_ostream &os, const SMTEmissionOptions &options=SMTEmissionOptions())
Run the ExportSMTLIB pass.
void registerExportSMTLIBTranslation()
Register the ExportSMTLIB pass.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Emission options for the ExportSMTLIB pass.
bool inlineSingleUseValues