CIRCT 24.0.0git
Loading...
Searching...
No Matches
LowerSMTToZ3LLVM.cpp
Go to the documentation of this file.
1//===- LowerSMTToZ3LLVM.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/ArithToLLVM/ArithToLLVM.h"
15#include "mlir/Conversion/ControlFlowToLLVM/ControlFlowToLLVM.h"
16#include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVM.h"
17#include "mlir/Conversion/LLVMCommon/ConversionTarget.h"
18#include "mlir/Conversion/LLVMCommon/TypeConverter.h"
19#include "mlir/Conversion/SCFToControlFlow/SCFToControlFlow.h"
20#include "mlir/Dialect/ControlFlow/IR/ControlFlow.h"
21#include "mlir/Dialect/Func/IR/FuncOps.h"
22#include "mlir/Dialect/LLVMIR/FunctionCallUtils.h"
23#include "mlir/Dialect/LLVMIR/LLVMAttrs.h"
24#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
25#include "mlir/Dialect/SCF/IR/SCF.h"
26#include "mlir/Dialect/SMT/IR/SMTOps.h"
27#include "mlir/IR/BuiltinDialect.h"
28#include "mlir/Interfaces/FunctionInterfaces.h"
29#include "mlir/Pass/Pass.h"
30#include "mlir/Transforms/DialectConversion.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/ADT/StringMap.h"
34#include "llvm/ADT/TypeSwitch.h"
35#include "llvm/Support/Debug.h"
36
37#define DEBUG_TYPE "lower-smt-to-z3-llvm"
38
39namespace circt {
40#define GEN_PASS_DEF_LOWERSMTTOZ3LLVM
41#include "circt/Conversion/Passes.h.inc"
42} // namespace circt
43
44using namespace mlir;
45using namespace circt;
46using namespace smt;
47
48//===----------------------------------------------------------------------===//
49// SMTGlobalHandler implementation
50//===----------------------------------------------------------------------===//
51
53 ModuleOp module) {
54 OpBuilder::InsertionGuard guard(builder);
55 builder.setInsertionPointToStart(module.getBody());
56
57 SymbolCache symCache;
58 symCache.addDefinitions(module);
60 names.add(symCache);
61
62 Location loc = module.getLoc();
63 auto ptrTy = LLVM::LLVMPointerType::get(builder.getContext());
64
65 auto createGlobal = [&](StringRef namePrefix) {
66 auto global = LLVM::GlobalOp::create(
67 builder, loc, ptrTy, false, LLVM::Linkage::Internal,
68 names.newName(namePrefix), Attribute{}, /*alignment=*/8);
69 OpBuilder::InsertionGuard g(builder);
70 builder.createBlock(&global.getInitializer());
71 Value res = LLVM::ZeroOp::create(builder, loc, ptrTy);
72 LLVM::ReturnOp::create(builder, loc, res);
73 return global;
74 };
75
76 auto ctxGlobal = createGlobal("ctx");
77 auto solverGlobal = createGlobal("solver");
78
79 return SMTGlobalsHandler(std::move(names), solverGlobal, ctxGlobal);
80}
81
83 mlir::LLVM::GlobalOp solver,
84 mlir::LLVM::GlobalOp ctx)
85 : solver(solver), ctx(ctx), names(names) {}
86
88 mlir::LLVM::GlobalOp solver,
89 mlir::LLVM::GlobalOp ctx)
90 : solver(solver), ctx(ctx) {
91 SymbolCache symCache;
92 symCache.addDefinitions(module);
93 names.add(symCache);
94}
95
96//===----------------------------------------------------------------------===//
97// Lowering Pattern Base
98//===----------------------------------------------------------------------===//
99
100namespace {
101
102template <typename OpTy>
103class SMTLoweringPattern : public OpConversionPattern<OpTy> {
104public:
105 SMTLoweringPattern(const TypeConverter &typeConverter, MLIRContext *context,
106 SMTGlobalsHandler &globals,
107 const LowerSMTToZ3LLVMOptions &options)
108 : OpConversionPattern<OpTy>(typeConverter, context), globals(globals),
109 options(options) {}
110
111private:
112 Value buildGlobalPtrToGlobal(OpBuilder &builder, Location loc,
113 LLVM::GlobalOp global,
114 DenseMap<Block *, Value> &cache) const {
115 Block *block = builder.getBlock();
116 if (auto iter = cache.find(block); iter != cache.end())
117 return iter->getSecond();
118
119 OpBuilder::InsertionGuard g(builder);
120 builder.setInsertionPointToStart(block);
121 Value globalAddr = LLVM::AddressOfOp::create(builder, loc, global);
122 return cache[block] = LLVM::LoadOp::create(
123 builder, loc, LLVM::LLVMPointerType::get(builder.getContext()),
124 globalAddr);
125 }
126
127protected:
128 LLVM::LLVMFuncOp getOrCreateFunction(OpBuilder &builder, StringRef name,
129 LLVM::LLVMFunctionType funcType) const {
130 auto &funcOp = globals.funcMap[builder.getStringAttr(name)];
131 if (funcOp)
132 return funcOp;
133
134 OpBuilder::InsertionGuard guard(builder);
135 auto module = builder.getBlock()->getParent()->getParentOfType<ModuleOp>();
136 builder.setInsertionPointToEnd(module.getBody());
137 auto funcOpResult =
138 LLVM::lookupOrCreateFn(builder, module, name, funcType.getParams(),
139 funcType.getReturnType(), funcType.getVarArg());
140 assert(succeeded(funcOpResult) &&
141 "expected to create function declaration");
142 return funcOp = funcOpResult.value();
143 }
144
145 /// A convenience function to get the pointer to the context from the 'global'
146 /// operation. The result is cached for each basic block, i.e., it is assumed
147 /// that this function is never called in the same basic block again at a
148 /// location (insertion point of the 'builder') not dominating all previous
149 /// locations this function was called at.
150 Value buildContextPtr(OpBuilder &builder, Location loc) const {
151 return buildGlobalPtrToGlobal(builder, loc, globals.ctx, globals.ctxCache);
152 }
153
154 /// A convenience function to get the pointer to the solver from the 'global'
155 /// operation. The result is cached for each basic block, i.e., it is assumed
156 /// that this function is never called in the same basic block again at a
157 /// location (insertion point of the 'builder') not dominating all previous
158 /// locations this function was called at.
159 Value buildSolverPtr(OpBuilder &builder, Location loc) const {
160 return buildGlobalPtrToGlobal(builder, loc, globals.solver,
161 globals.solverCache);
162 }
163
164 /// Create a `llvm.call` operation to a function with the given 'name' and
165 /// 'type'. If there does not already exist a (external) function with that
166 /// name create a matching external function declaration.
167 LLVM::CallOp buildCall(OpBuilder &builder, Location loc, StringRef name,
168 LLVM::LLVMFunctionType funcType,
169 ValueRange args) const {
170 auto funcOp = getOrCreateFunction(builder, name, funcType);
171 return LLVM::CallOp::create(builder, loc, funcOp, args);
172 }
173
174 /// Build a global constant for the given string and construct an 'addressof'
175 /// operation at the current 'builder' insertion point to get a pointer to it.
176 /// Multiple calls with the same string will reuse the same global. It is
177 /// guaranteed that the symbol of the global will be unique.
178 Value buildString(OpBuilder &builder, Location loc, StringRef str) const {
179 auto &global = globals.stringCache[builder.getStringAttr(str)];
180 if (!global) {
181 OpBuilder::InsertionGuard guard(builder);
182 auto module =
183 builder.getBlock()->getParent()->getParentOfType<ModuleOp>();
184 builder.setInsertionPointToEnd(module.getBody());
185 auto arrayTy =
186 LLVM::LLVMArrayType::get(builder.getI8Type(), str.size() + 1);
187 auto strAttr = builder.getStringAttr(str.str() + '\00');
188 global = LLVM::GlobalOp::create(
189 builder, loc, arrayTy, /*isConstant=*/true, LLVM::Linkage::Internal,
190 globals.names.newName("str"), strAttr);
191 }
192 return LLVM::AddressOfOp::create(builder, loc, global);
193 }
194 /// Most API functions require a pointer to the the Z3 context object as the
195 /// first argument. This helper function prepends this pointer value to the
196 /// call for convenience.
197 LLVM::CallOp buildAPICallWithContext(OpBuilder &builder, Location loc,
198 StringRef name, Type returnType,
199 ValueRange args = {}) const {
200 auto ctx = buildContextPtr(builder, loc);
201 SmallVector<Value> arguments;
202 arguments.emplace_back(ctx);
203 arguments.append(SmallVector<Value>(args));
204 return buildCall(
205 builder, loc, name,
206 LLVM::LLVMFunctionType::get(
207 returnType, SmallVector<Type>(ValueRange(arguments).getTypes())),
208 arguments);
209 }
210
211 /// Most API functions we need to call return a 'Z3_AST' object which is a
212 /// pointer in LLVM. This helper function simplifies calling those API
213 /// functions.
214 Value buildPtrAPICall(OpBuilder &builder, Location loc, StringRef name,
215 ValueRange args = {}) const {
216 return buildAPICallWithContext(
217 builder, loc, name,
218 LLVM::LLVMPointerType::get(builder.getContext()), args)
219 ->getResult(0);
220 }
221
222 /// Build a value representing the SMT sort given with 'type'.
223 Value buildSort(OpBuilder &builder, Location loc, Type type) const {
224 // NOTE: if a type not handled by this switch is passed, an assertion will
225 // be triggered.
226 return TypeSwitch<Type, Value>(type)
227 .Case([&](smt::IntType ty) {
228 return buildPtrAPICall(builder, loc, "Z3_mk_int_sort");
229 })
230 .Case([&](smt::BitVectorType ty) {
231 Value bitwidth = LLVM::ConstantOp::create(
232 builder, loc, builder.getI32Type(), ty.getWidth());
233 return buildPtrAPICall(builder, loc, "Z3_mk_bv_sort", {bitwidth});
234 })
235 .Case([&](smt::BoolType ty) {
236 return buildPtrAPICall(builder, loc, "Z3_mk_bool_sort");
237 })
238 .Case([&](smt::SortType ty) {
239 Value str = buildString(builder, loc, ty.getIdentifier());
240 Value sym =
241 buildPtrAPICall(builder, loc, "Z3_mk_string_symbol", {str});
242 return buildPtrAPICall(builder, loc, "Z3_mk_uninterpreted_sort",
243 {sym});
244 })
245 .Case([&](smt::ArrayType ty) {
246 return buildPtrAPICall(builder, loc, "Z3_mk_array_sort",
247 {buildSort(builder, loc, ty.getDomainType()),
248 buildSort(builder, loc, ty.getRangeType())});
249 });
250 }
251
252 SMTGlobalsHandler &globals;
253 const LowerSMTToZ3LLVMOptions &options;
254};
255
256//===----------------------------------------------------------------------===//
257// Lowering Patterns
258//===----------------------------------------------------------------------===//
259
260/// The 'smt.declare_fun' operation is used to declare both constants and
261/// functions. The Z3 API, however, uses two different functions. Therefore,
262/// depending on the result type of this operation, one of the following two
263/// API functions is used to create the symbolic value:
264/// ```
265/// Z3_ast Z3_API Z3_mk_fresh_const(Z3_context c, Z3_string prefix, Z3_sort ty);
266/// Z3_func_decl Z3_API Z3_mk_fresh_func_decl(
267/// Z3_context c, Z3_string prefix, unsigned domain_size,
268/// Z3_sort const domain[], Z3_sort range);
269/// ```
270struct DeclareFunOpLowering : public SMTLoweringPattern<DeclareFunOp> {
271 using SMTLoweringPattern::SMTLoweringPattern;
272
273 LogicalResult
274 matchAndRewrite(DeclareFunOp op, OpAdaptor adaptor,
275 ConversionPatternRewriter &rewriter) const final {
276 Location loc = op.getLoc();
277
278 // Create the name prefix.
279 Value prefix;
280 if (adaptor.getNamePrefix())
281 prefix = buildString(rewriter, loc, *adaptor.getNamePrefix());
282 else
283 prefix = LLVM::ZeroOp::create(rewriter, loc,
284 LLVM::LLVMPointerType::get(getContext()));
285
286 // Handle the constant value case.
287 if (!isa<SMTFuncType>(op.getType())) {
288 Value sort = buildSort(rewriter, loc, op.getType());
289 Value constDecl =
290 buildPtrAPICall(rewriter, loc, "Z3_mk_fresh_const", {prefix, sort});
291 rewriter.replaceOp(op, constDecl);
292 return success();
293 }
294
295 // Otherwise, we declare a function.
296 Type llvmPtrTy = LLVM::LLVMPointerType::get(getContext());
297 auto funcType = cast<SMTFuncType>(op.getResult().getType());
298 Value rangeSort = buildSort(rewriter, loc, funcType.getRangeType());
299
300 Type arrTy =
301 LLVM::LLVMArrayType::get(llvmPtrTy, funcType.getDomainTypes().size());
302
303 Value domain = LLVM::UndefOp::create(rewriter, loc, arrTy);
304 for (auto [i, ty] : llvm::enumerate(funcType.getDomainTypes())) {
305 Value sort = buildSort(rewriter, loc, ty);
306 domain = LLVM::InsertValueOp::create(rewriter, loc, domain, sort, i);
307 }
308
309 Value one =
310 LLVM::ConstantOp::create(rewriter, loc, rewriter.getI32Type(), 1);
311 Value domainStorage =
312 LLVM::AllocaOp::create(rewriter, loc, llvmPtrTy, arrTy, one);
313 LLVM::StoreOp::create(rewriter, loc, domain, domainStorage);
314
315 Value domainSize = LLVM::ConstantOp::create(
316 rewriter, loc, rewriter.getI32Type(), funcType.getDomainTypes().size());
317 Value decl =
318 buildPtrAPICall(rewriter, loc, "Z3_mk_fresh_func_decl",
319 {prefix, domainSize, domainStorage, rangeSort});
320
321 rewriter.replaceOp(op, decl);
322 return success();
323 }
324};
325
326/// Lower the 'smt.apply_func' operation to Z3 API calls of the form:
327/// ```
328/// Z3_ast Z3_API Z3_mk_app(Z3_context c, Z3_func_decl d,
329/// unsigned num_args, Z3_ast const args[]);
330/// ```
331struct ApplyFuncOpLowering : public SMTLoweringPattern<ApplyFuncOp> {
332 using SMTLoweringPattern::SMTLoweringPattern;
333
334 LogicalResult
335 matchAndRewrite(ApplyFuncOp op, OpAdaptor adaptor,
336 ConversionPatternRewriter &rewriter) const final {
337 Location loc = op.getLoc();
338 Type llvmPtrTy = LLVM::LLVMPointerType::get(getContext());
339 Type arrTy = LLVM::LLVMArrayType::get(llvmPtrTy, adaptor.getArgs().size());
340
341 // Create an array of the function arguments.
342 Value domain = LLVM::UndefOp::create(rewriter, loc, arrTy);
343 for (auto [i, arg] : llvm::enumerate(adaptor.getArgs()))
344 domain = LLVM::InsertValueOp::create(rewriter, loc, domain, arg, i);
345
346 // Store the array on the stack.
347 Value one =
348 LLVM::ConstantOp::create(rewriter, loc, rewriter.getI32Type(), 1);
349 Value domainStorage =
350 LLVM::AllocaOp::create(rewriter, loc, llvmPtrTy, arrTy, one);
351 LLVM::StoreOp::create(rewriter, loc, domain, domainStorage);
352
353 // Call the API function with a pointer to the function, the number of
354 // arguments, and the pointer to the arguments stored on the stack.
355 Value domainSize = LLVM::ConstantOp::create(
356 rewriter, loc, rewriter.getI32Type(), adaptor.getArgs().size());
357 Value returnVal =
358 buildPtrAPICall(rewriter, loc, "Z3_mk_app",
359 {adaptor.getFunc(), domainSize, domainStorage});
360 rewriter.replaceOp(op, returnVal);
361
362 return success();
363 }
364};
365
366/// Lower the `smt.bv.constant` operation to either
367/// ```
368/// Z3_ast Z3_API Z3_mk_unsigned_int64(Z3_context c, uint64_t v, Z3_sort ty);
369/// ```
370/// if the bit-vector fits into a 64-bit integer or convert it to a string and
371/// use the sligtly slower but arbitrary precision API function:
372/// ```
373/// Z3_ast Z3_API Z3_mk_numeral(Z3_context c, Z3_string numeral, Z3_sort ty);
374/// ```
375/// Note that there is also an API function taking an array of booleans, and
376/// while those are typically compiled to 'i8' in LLVM they don't necessarily
377/// have to (I think).
378struct BVConstantOpLowering : public SMTLoweringPattern<smt::BVConstantOp> {
379 using SMTLoweringPattern::SMTLoweringPattern;
380
381 LogicalResult
382 matchAndRewrite(smt::BVConstantOp op, OpAdaptor adaptor,
383 ConversionPatternRewriter &rewriter) const final {
384 Location loc = op.getLoc();
385 unsigned width = op.getType().getWidth();
386 auto bvSort = buildSort(rewriter, loc, op.getResult().getType());
387 APInt val = adaptor.getValue().getValue();
388
389 if (width <= 64) {
390 Value bvConst = LLVM::ConstantOp::create(
391 rewriter, loc, rewriter.getI64Type(), val.getZExtValue());
392 Value res = buildPtrAPICall(rewriter, loc, "Z3_mk_unsigned_int64",
393 {bvConst, bvSort});
394 rewriter.replaceOp(op, res);
395 return success();
396 }
397
398 std::string str;
399 llvm::raw_string_ostream stream(str);
400 stream << val;
401 Value bvString = buildString(rewriter, loc, str);
402 Value bvNumeral =
403 buildPtrAPICall(rewriter, loc, "Z3_mk_numeral", {bvString, bvSort});
404
405 rewriter.replaceOp(op, bvNumeral);
406 return success();
407 }
408};
409
410/// Some of the Z3 API supports a variadic number of operands for some
411/// operations (in particular if the expansion would lead to a super-linear
412/// increase in operations such as with the ':pairwise' attribute). Those API
413/// calls take an 'unsigned' argument indicating the size of an array of
414/// pointers to the operands.
415template <typename SourceTy>
416struct VariadicSMTPattern : public SMTLoweringPattern<SourceTy> {
417 using OpAdaptor = typename SMTLoweringPattern<SourceTy>::OpAdaptor;
418
419 VariadicSMTPattern(const TypeConverter &typeConverter, MLIRContext *context,
420 SMTGlobalsHandler &globals,
421 const LowerSMTToZ3LLVMOptions &options,
422 StringRef apiFuncName, unsigned minNumArgs)
423 : SMTLoweringPattern<SourceTy>(typeConverter, context, globals, options),
424 apiFuncName(apiFuncName), minNumArgs(minNumArgs) {}
425
426 LogicalResult
427 matchAndRewrite(SourceTy op, OpAdaptor adaptor,
428 ConversionPatternRewriter &rewriter) const final {
429 if (adaptor.getOperands().size() < minNumArgs)
430 return failure();
431
432 Location loc = op.getLoc();
433 Value numOperands = LLVM::ConstantOp::create(
434 rewriter, loc, rewriter.getI32Type(), op->getNumOperands());
435 Value constOne =
436 LLVM::ConstantOp::create(rewriter, loc, rewriter.getI32Type(), 1);
437 Type ptrTy = LLVM::LLVMPointerType::get(rewriter.getContext());
438 Type arrTy = LLVM::LLVMArrayType::get(ptrTy, op->getNumOperands());
439 Value storage =
440 LLVM::AllocaOp::create(rewriter, loc, ptrTy, arrTy, constOne);
441 Value array = LLVM::UndefOp::create(rewriter, loc, arrTy);
442
443 for (auto [i, operand] : llvm::enumerate(adaptor.getOperands()))
444 array = LLVM::InsertValueOp::create(rewriter, loc, array, operand,
445 ArrayRef<int64_t>{(int64_t)i});
446
447 LLVM::StoreOp::create(rewriter, loc, array, storage);
448
449 rewriter.replaceOp(op,
450 SMTLoweringPattern<SourceTy>::buildPtrAPICall(
451 rewriter, loc, apiFuncName, {numOperands, storage}));
452 return success();
453 }
454
455private:
456 StringRef apiFuncName;
457 unsigned minNumArgs;
458};
459
460/// Lower an SMT operation to a function call with the name 'apiFuncName' with
461/// arguments matching the operands one-to-one.
462template <typename SourceTy>
463struct OneToOneSMTPattern : public SMTLoweringPattern<SourceTy> {
464 using OpAdaptor = typename SMTLoweringPattern<SourceTy>::OpAdaptor;
465
466 OneToOneSMTPattern(const TypeConverter &typeConverter, MLIRContext *context,
467 SMTGlobalsHandler &globals,
468 const LowerSMTToZ3LLVMOptions &options,
469 StringRef apiFuncName, unsigned numOperands)
470 : SMTLoweringPattern<SourceTy>(typeConverter, context, globals, options),
471 apiFuncName(apiFuncName), numOperands(numOperands) {}
472
473 LogicalResult
474 matchAndRewrite(SourceTy op, OpAdaptor adaptor,
475 ConversionPatternRewriter &rewriter) const final {
476 if (adaptor.getOperands().size() != numOperands)
477 return failure();
478
479 rewriter.replaceOp(
480 op, SMTLoweringPattern<SourceTy>::buildPtrAPICall(
481 rewriter, op.getLoc(), apiFuncName, adaptor.getOperands()));
482 return success();
483 }
484
485private:
486 StringRef apiFuncName;
487 unsigned numOperands;
488};
489
490/// A pattern to lower SMT operations with a variadic number of operands
491/// modelling the ':chainable' attribute in SMT to binary operations.
492template <typename SourceTy>
493class LowerChainableSMTPattern : public SMTLoweringPattern<SourceTy> {
494 using SMTLoweringPattern<SourceTy>::SMTLoweringPattern;
495 using OpAdaptor = typename SMTLoweringPattern<SourceTy>::OpAdaptor;
496
497 LogicalResult
498 matchAndRewrite(SourceTy op, OpAdaptor adaptor,
499 ConversionPatternRewriter &rewriter) const final {
500 if (adaptor.getOperands().size() <= 2)
501 return failure();
502
503 Location loc = op.getLoc();
504 SmallVector<Value> elements;
505 for (int i = 1, e = adaptor.getOperands().size(); i < e; ++i) {
506 Value val = SourceTy::create(
507 rewriter, loc, op->getResultTypes(),
508 ValueRange{adaptor.getOperands()[i - 1], adaptor.getOperands()[i]});
509 elements.push_back(val);
510 }
511 rewriter.replaceOpWithNewOp<smt::AndOp>(op, elements);
512 return success();
513 }
514};
515
516/// A pattern to lower SMT operations with a variadic number of operands
517/// modelling the `:left-assoc` attribute to a sequence of binary operators.
518template <typename SourceTy>
519class LowerLeftAssocSMTPattern : public SMTLoweringPattern<SourceTy> {
520 using SMTLoweringPattern<SourceTy>::SMTLoweringPattern;
521 using OpAdaptor = typename SMTLoweringPattern<SourceTy>::OpAdaptor;
522
523 LogicalResult
524 matchAndRewrite(SourceTy op, OpAdaptor adaptor,
525 ConversionPatternRewriter &rewriter) const final {
526 if (adaptor.getOperands().size() <= 2)
527 return rewriter.notifyMatchFailure(op, "must have at least two operands");
528
529 Value runner = adaptor.getOperands()[0];
530 for (Value val : adaptor.getOperands().drop_front())
531 runner = SourceTy::create(rewriter, op.getLoc(), op->getResultTypes(),
532 ValueRange{runner, val});
533
534 rewriter.replaceOp(op, runner);
535 return success();
536 }
537};
538
539/// The 'smt.solver' operation has a region that corresponds to the lifetime of
540/// the Z3 context and one solver instance created within this context.
541/// To create a context, a Z3 configuration has to be built first and various
542/// configuration parameters can be set before creating a context from it. Once
543/// we have a context, we can create a solver and store a pointer to the context
544/// and the solver in an LLVM global such that operations in the child region
545/// have access to them. While the context created with `Z3_mk_context` takes
546/// care of the reference counting of `Z3_AST` objects, it still requires manual
547/// reference counting of `Z3_solver` objects, therefore, we need to increase
548/// the ref. counter of the solver we get from `Z3_mk_solver` and must decrease
549/// it again once we don't need it anymore. Finally, the configuration object
550/// can be deleted.
551/// ```
552/// Z3_config Z3_API Z3_mk_config(void);
553/// void Z3_API Z3_set_param_value(Z3_config c, Z3_string param_id,
554/// Z3_string param_value);
555/// Z3_context Z3_API Z3_mk_context(Z3_config c);
556/// Z3_solver Z3_API Z3_mk_solver(Z3_context c);
557/// void Z3_API Z3_solver_inc_ref(Z3_context c, Z3_solver s);
558/// void Z3_API Z3_del_config(Z3_config c);
559/// ```
560/// At the end of the solver lifetime, we have to tell the context that we
561/// don't need the solver anymore and delete the context itself.
562/// ```
563/// void Z3_API Z3_solver_dec_ref(Z3_context c, Z3_solver s);
564/// void Z3_API Z3_del_context(Z3_context c);
565/// ```
566/// Note that the solver created here is a combined solver. There might be some
567/// potential for optimization by creating more specialized solvers supported by
568/// the Z3 API according the the kind of operations present in the body region.
569struct SolverOpLowering : public SMTLoweringPattern<SolverOp> {
570 using SMTLoweringPattern::SMTLoweringPattern;
571
572 LogicalResult
573 matchAndRewrite(SolverOp op, OpAdaptor adaptor,
574 ConversionPatternRewriter &rewriter) const final {
575 Location loc = op.getLoc();
576 auto ptrTy = LLVM::LLVMPointerType::get(getContext());
577 auto voidTy = LLVM::LLVMVoidType::get(getContext());
578 auto ptrToPtrFunc = LLVM::LLVMFunctionType::get(ptrTy, ptrTy);
579 auto ptrPtrToPtrFunc = LLVM::LLVMFunctionType::get(ptrTy, {ptrTy, ptrTy});
580 auto ptrToVoidFunc = LLVM::LLVMFunctionType::get(voidTy, ptrTy);
581 auto ptrPtrToVoidFunc = LLVM::LLVMFunctionType::get(voidTy, {ptrTy, ptrTy});
582
583 // Create the configuration.
584 Value config = buildCall(rewriter, loc, "Z3_mk_config",
585 LLVM::LLVMFunctionType::get(ptrTy, {}), {})
586 .getResult();
587
588 // In debug-mode, we enable proofs such that we can fetch one in the 'unsat'
589 // region of each 'smt.check' operation.
590 if (options.debug) {
591 Value paramKey = buildString(rewriter, loc, "proof");
592 Value paramValue = buildString(rewriter, loc, "true");
593 buildCall(rewriter, loc, "Z3_set_param_value",
594 LLVM::LLVMFunctionType::get(voidTy, {ptrTy, ptrTy, ptrTy}),
595 {config, paramKey, paramValue});
596 }
597
598 // Check if the logic is set anywhere within the solver
599 std::optional<StringRef> logic = std::nullopt;
600 auto setLogicOps = op.getBodyRegion().getOps<smt::SetLogicOp>();
601 if (!setLogicOps.empty()) {
602 // We know from before patterns were applied that there is only one
603 // set_logic op
604 auto setLogicOp = *setLogicOps.begin();
605 logic = setLogicOp.getLogic();
606 rewriter.eraseOp(setLogicOp);
607 }
608
609 // Create the context and store a pointer to it in the global variable.
610 Value ctx = buildCall(rewriter, loc, "Z3_mk_context", ptrToPtrFunc, config)
611 .getResult();
612 Value ctxAddr =
613 LLVM::AddressOfOp::create(rewriter, loc, globals.ctx).getResult();
614 LLVM::StoreOp::create(rewriter, loc, ctx, ctxAddr);
615
616 // Delete the configuration again.
617 buildCall(rewriter, loc, "Z3_del_config", ptrToVoidFunc, {config});
618
619 // Create a solver instance, increase its reference counter, and store a
620 // pointer to it in the global variable.
621 Value solver;
622 if (logic) {
623 auto logicStr = buildString(rewriter, loc, logic.value());
624 solver = buildCall(rewriter, loc, "Z3_mk_solver_for_logic",
625 ptrPtrToPtrFunc, {ctx, logicStr})
626 ->getResult(0);
627 } else {
628 solver = buildCall(rewriter, loc, "Z3_mk_solver", ptrToPtrFunc, ctx)
629 ->getResult(0);
630 }
631 buildCall(rewriter, loc, "Z3_solver_inc_ref", ptrPtrToVoidFunc,
632 {ctx, solver});
633 Value solverAddr =
634 LLVM::AddressOfOp::create(rewriter, loc, globals.solver).getResult();
635 LLVM::StoreOp::create(rewriter, loc, solver, solverAddr);
636
637 // This assumes that no constant hoisting of the like happens inbetween
638 // the patterns defined in this pass because once the solver initialization
639 // and deallocation calls are inserted and the body region is inlined,
640 // canonicalizations and folders applied inbetween lowering patterns might
641 // hoist the SMT constants which means they would access uninitialized
642 // global variables once they are lowered.
643 SmallVector<Type> convertedTypes;
644 if (failed(
645 typeConverter->convertTypes(op->getResultTypes(), convertedTypes)))
646 return failure();
647
648 // Solver regions are outlined below. If one contains a trace marker,
649 // forward the enclosing function's trace context through the outlined
650 // function.
651 bool containsBMCTrace = false;
652 op.getBodyRegion().walk(
653 [&](verif::BMCTraceOp) { containsBMCTrace = true; });
654 Value traceContext;
655 SmallVector<Type> inputTypes(adaptor.getInputs().getTypes());
656 SmallVector<Value> callOperands(adaptor.getInputs());
657 if (containsBMCTrace) {
658 auto parentFunction = op->getParentOfType<FunctionOpInterface>();
659 if (!parentFunction || parentFunction.getNumArguments() == 0)
660 return rewriter.notifyMatchFailure(op, "missing BMC trace context");
661 traceContext =
662 parentFunction.getArgument(parentFunction.getNumArguments() - 1);
663 if (!isa<LLVM::LLVMPointerType>(traceContext.getType()))
664 return rewriter.notifyMatchFailure(op,
665 "invalid BMC trace context type");
666 inputTypes.push_back(traceContext.getType());
667 callOperands.push_back(traceContext);
668 op.getBodyRegion().addArgument(traceContext.getType(), loc);
669
670 if (options.printOnlyFirstCounterexample) {
671 // Keep the optional one-shot printing policy in the generated code.
672 // This flag is local to one solver invocation and shared by every
673 // dynamic execution of an smt.check in the outlined solver body.
674 Value one =
675 LLVM::ConstantOp::create(rewriter, loc, rewriter.getI32Type(), 1);
676 Value traceEmittedStorage = LLVM::AllocaOp::create(
677 rewriter, loc, ptrTy, rewriter.getI1Type(), one);
678 Value notEmitted =
679 LLVM::ConstantOp::create(rewriter, loc, rewriter.getI1Type(), 0);
680 LLVM::StoreOp::create(rewriter, loc, notEmitted, traceEmittedStorage);
681 inputTypes.push_back(traceEmittedStorage.getType());
682 callOperands.push_back(traceEmittedStorage);
683 op.getBodyRegion().addArgument(traceEmittedStorage.getType(), loc);
684 }
685 }
686
687 func::FuncOp funcOp;
688 {
689 OpBuilder::InsertionGuard guard(rewriter);
690 auto module = op->getParentOfType<ModuleOp>();
691 rewriter.setInsertionPointToEnd(module.getBody());
692
693 funcOp = func::FuncOp::create(
694 rewriter, loc, globals.names.newName("solver"),
695 rewriter.getFunctionType(inputTypes, convertedTypes));
696 if (containsBMCTrace) {
697 globals.traceFunctionNames.insert(funcOp.getSymNameAttr());
698 if (options.printOnlyFirstCounterexample)
699 globals.traceEmissionFunctionNames.insert(funcOp.getSymNameAttr());
700 }
701 rewriter.inlineRegionBefore(op.getBodyRegion(), funcOp.getBody(),
702 funcOp.end());
703 }
704
705 ValueRange results =
706 func::CallOp::create(rewriter, loc, funcOp, callOperands)->getResults();
707
708 // At the end of the region, decrease the solver's reference counter and
709 // delete the context.
710 // NOTE: we cannot use the convenience helper here because we don't want to
711 // load the context from the global but use the result from the 'mk_context'
712 // call directly for two reasons:
713 // * avoid an unnecessary load
714 // * the caching mechanism of the context does not work here because it
715 // would reuse the loaded context from a earlier solver
716 buildCall(rewriter, loc, "Z3_solver_dec_ref", ptrPtrToVoidFunc,
717 {ctx, solver});
718 buildCall(rewriter, loc, "Z3_del_context", ptrToVoidFunc, ctx);
719
720 rewriter.replaceOp(op, results);
721 return success();
722 }
723};
724
725/// Lower `smt.assert` operations to Z3 API calls of the form:
726/// ```
727/// void Z3_API Z3_solver_assert(Z3_context c, Z3_solver s, Z3_ast a);
728/// ```
729struct AssertOpLowering : public SMTLoweringPattern<AssertOp> {
730 using SMTLoweringPattern::SMTLoweringPattern;
731
732 LogicalResult
733 matchAndRewrite(AssertOp op, OpAdaptor adaptor,
734 ConversionPatternRewriter &rewriter) const final {
735 Location loc = op.getLoc();
736 buildAPICallWithContext(
737 rewriter, loc, "Z3_solver_assert",
738 LLVM::LLVMVoidType::get(getContext()),
739 {buildSolverPtr(rewriter, loc), adaptor.getInput()});
740
741 rewriter.eraseOp(op);
742 return success();
743 }
744};
745
746/// Lower `smt.reset` operations to Z3 API calls of the form:
747/// ```
748/// void Z3_API Z3_solver_reset(Z3_context c, Z3_solver s);
749/// ```
750struct ResetOpLowering : public SMTLoweringPattern<ResetOp> {
751 using SMTLoweringPattern::SMTLoweringPattern;
752
753 LogicalResult
754 matchAndRewrite(ResetOp op, OpAdaptor adaptor,
755 ConversionPatternRewriter &rewriter) const final {
756 Location loc = op.getLoc();
757 buildAPICallWithContext(rewriter, loc, "Z3_solver_reset",
758 LLVM::LLVMVoidType::get(getContext()),
759 {buildSolverPtr(rewriter, loc)});
760
761 rewriter.eraseOp(op);
762 return success();
763 }
764};
765
766/// Lower `smt.push` operations to (repeated) Z3 API calls of the form:
767/// ```
768/// void Z3_API Z3_solver_push(Z3_context c, Z3_solver s);
769/// ```
770struct PushOpLowering : public SMTLoweringPattern<PushOp> {
771 using SMTLoweringPattern::SMTLoweringPattern;
772 LogicalResult
773 matchAndRewrite(PushOp op, OpAdaptor adaptor,
774 ConversionPatternRewriter &rewriter) const final {
775 Location loc = op.getLoc();
776 // SMTLIB allows multiple levels to be pushed with one push command, but the
777 // Z3 C API doesn't let you provide a number of levels for push calls so
778 // multiple calls have to be created.
779 for (uint32_t i = 0; i < op.getCount(); i++)
780 buildAPICallWithContext(rewriter, loc, "Z3_solver_push",
781 LLVM::LLVMVoidType::get(getContext()),
782 {buildSolverPtr(rewriter, loc)});
783 rewriter.eraseOp(op);
784 return success();
785 }
786};
787
788/// Lower `smt.pop` operations to Z3 API calls of the form:
789/// ```
790/// void Z3_API Z3_solver_pop(Z3_context c, Z3_solver s, unsigned n);
791/// ```
792struct PopOpLowering : public SMTLoweringPattern<PopOp> {
793 using SMTLoweringPattern::SMTLoweringPattern;
794 LogicalResult
795 matchAndRewrite(PopOp op, OpAdaptor adaptor,
796 ConversionPatternRewriter &rewriter) const final {
797 Location loc = op.getLoc();
798 Value constVal = LLVM::ConstantOp::create(
799 rewriter, loc, rewriter.getI32Type(), op.getCount());
800 buildAPICallWithContext(rewriter, loc, "Z3_solver_pop",
801 LLVM::LLVMVoidType::get(getContext()),
802 {buildSolverPtr(rewriter, loc), constVal});
803 rewriter.eraseOp(op);
804 return success();
805 }
806};
807
808/// Lower `smt.yield` operations to `scf.yield` operations. This not necessary
809/// for the yield in `smt.solver` or in quantifiers since they are deleted
810/// directly by the parent operation, but makes the lowering of the `smt.check`
811/// operation simpler and more convenient since the regions get translated
812/// directly to regions of `scf.if` operations.
813struct YieldOpLowering : public SMTLoweringPattern<YieldOp> {
814 using SMTLoweringPattern::SMTLoweringPattern;
815
816 LogicalResult
817 matchAndRewrite(YieldOp op, OpAdaptor adaptor,
818 ConversionPatternRewriter &rewriter) const final {
819 if (op->getParentOfType<func::FuncOp>()) {
820 rewriter.replaceOpWithNewOp<func::ReturnOp>(op, adaptor.getValues());
821 return success();
822 }
823 if (op->getParentOfType<LLVM::LLVMFuncOp>()) {
824 rewriter.replaceOpWithNewOp<LLVM::ReturnOp>(op, adaptor.getValues());
825 return success();
826 }
827 if (isa_and_nonnull<scf::SCFDialect>(op->getParentOp()->getDialect())) {
828 rewriter.replaceOpWithNewOp<scf::YieldOp>(op, adaptor.getValues());
829 return success();
830 }
831 return failure();
832 }
833};
834
835/// Lower `smt.check` operations to Z3 API calls and control-flow operations.
836/// ```
837/// Z3_lbool Z3_API Z3_solver_check(Z3_context c, Z3_solver s);
838///
839/// typedef enum
840/// {
841/// Z3_L_FALSE = -1, // means unsatisfiable here
842/// Z3_L_UNDEF, // means unknown here
843/// Z3_L_TRUE // means satisfiable here
844/// } Z3_lbool;
845/// ```
846struct CheckOpLowering : public SMTLoweringPattern<CheckOp> {
847 using SMTLoweringPattern::SMTLoweringPattern;
848
849 LogicalResult
850 matchAndRewrite(CheckOp op, OpAdaptor adaptor,
851 ConversionPatternRewriter &rewriter) const final {
852 Location loc = op.getLoc();
853 auto ptrTy = LLVM::LLVMPointerType::get(rewriter.getContext());
854 auto printfType = LLVM::LLVMFunctionType::get(
855 LLVM::LLVMVoidType::get(rewriter.getContext()), {ptrTy}, true);
856
857 auto getHeaderString = [](const std::string &title) {
858 unsigned titleSize = title.size() + 2; // Add a space left and right
859 return std::string((80 - titleSize) / 2, '-') + " " + title + " " +
860 std::string((80 - titleSize + 1) / 2, '-') + "\n%s\n" +
861 std::string(80, '-') + "\n";
862 };
863
864 // Get the pointer to the solver instance.
865 Value solver = buildSolverPtr(rewriter, loc);
866
867 // In debug-mode, print the state of the solver before calling 'check-sat'
868 // on it. This prints the asserted SMT expressions.
869 if (options.debug) {
870 auto solverStringPtr =
871 buildPtrAPICall(rewriter, loc, "Z3_solver_to_string", {solver});
872 auto solverFormatString =
873 buildString(rewriter, loc, getHeaderString("Solver"));
874 buildCall(rewriter, op.getLoc(), "printf", printfType,
875 {solverFormatString, solverStringPtr});
876 }
877
878 // Convert the result types of the `smt.check` operation.
879 SmallVector<Type> resultTypes;
880 if (failed(typeConverter->convertTypes(op->getResultTypes(), resultTypes)))
881 return failure();
882
883 // Call 'check-sat' and check if the assertions are satisfiable.
884 Value checkResult =
885 buildAPICallWithContext(rewriter, loc, "Z3_solver_check",
886 rewriter.getI32Type(), {solver})
887 ->getResult(0);
888 Value constOne =
889 LLVM::ConstantOp::create(rewriter, loc, checkResult.getType(), 1);
890 Value isSat = LLVM::ICmpOp::create(rewriter, loc, LLVM::ICmpPredicate::eq,
891 checkResult, constOne);
892
893 // Simply inline the 'sat' region into the 'then' region of the 'scf.if'
894 auto satIfOp = scf::IfOp::create(rewriter, loc, resultTypes, isSat);
895 rewriter.inlineRegionBefore(op.getSatRegion(), satIfOp.getThenRegion(),
896 satIfOp.getThenRegion().end());
897
898 // Materialize a counterexample while the satisfying model and all recorded
899 // ASTs still belong to a live Z3 context. The Z3 function addresses are
900 // supplied by the JITed module so the BMC runtime remains independent of a
901 // particular Z3 library at link time.
902 auto parentFunction = op->getParentOfType<FunctionOpInterface>();
903 auto functionName = parentFunction
904 ? parentFunction->getAttrOfType<StringAttr>(
905 SymbolTable::getSymbolAttrName())
906 : StringAttr{};
907 Operation *traceEmissionOp = nullptr;
908 if (functionName && globals.traceFunctionNames.contains(functionName)) {
909 rewriter.setInsertionPointToStart(satIfOp.thenBlock());
910 bool printOnlyFirst =
911 globals.traceEmissionFunctionNames.contains(functionName);
912 Value traceContext = parentFunction.getArgument(
913 parentFunction.getNumArguments() - (printOnlyFirst ? 2 : 1));
914 Value traceEmittedStorage;
915 if (printOnlyFirst) {
916 traceEmittedStorage =
917 parentFunction.getArgument(parentFunction.getNumArguments() - 1);
918 Value traceEmitted = LLVM::LoadOp::create(
919 rewriter, loc, rewriter.getI1Type(), traceEmittedStorage);
920 Value notEmitted =
921 LLVM::ConstantOp::create(rewriter, loc, rewriter.getI1Type(), 0);
922 Value shouldEmit = LLVM::ICmpOp::create(
923 rewriter, loc, LLVM::ICmpPredicate::eq, traceEmitted, notEmitted);
924
925 auto traceIf = scf::IfOp::create(rewriter, loc, TypeRange{}, shouldEmit,
926 /*withThenRegion=*/true,
927 /*withElseRegion=*/false);
928 traceEmissionOp = traceIf.getOperation();
929 rewriter.setInsertionPointToStart(&traceIf.getThenRegion().front());
930 }
931 Value traceModel =
932 buildPtrAPICall(rewriter, loc, "Z3_solver_get_model", {solver});
933 Value context = buildContextPtr(rewriter, loc);
934
935 auto modelEvalType = LLVM::LLVMFunctionType::get(
936 rewriter.getI1Type(),
937 {ptrTy, ptrTy, ptrTy, rewriter.getI1Type(), ptrTy});
938 auto modelEval =
939 getOrCreateFunction(rewriter, "Z3_model_eval", modelEvalType);
940 Value modelEvalAddress =
941 LLVM::AddressOfOp::create(rewriter, loc, modelEval);
942
943 auto getNumeralType = LLVM::LLVMFunctionType::get(ptrTy, {ptrTy, ptrTy});
944 auto getNumeral = getOrCreateFunction(
945 rewriter, "Z3_get_numeral_binary_string", getNumeralType);
946 Value getNumeralAddress =
947 LLVM::AddressOfOp::create(rewriter, loc, getNumeral);
948
949 auto traceCall = buildCall(
950 rewriter, loc, "circt_bmc_print_trace",
951 LLVM::LLVMFunctionType::get(rewriter.getI1Type(),
952 {ptrTy, ptrTy, ptrTy, ptrTy, ptrTy}),
953 {traceContext, context, traceModel, modelEvalAddress,
954 getNumeralAddress});
955 if (printOnlyFirst) {
956 LLVM::StoreOp::create(rewriter, loc, traceCall.getResult(),
957 traceEmittedStorage);
958 scf::YieldOp::create(rewriter, loc);
959 } else {
960 traceEmissionOp = traceCall.getOperation();
961 }
962 }
963
964 // Print the model before the original SAT region, which may mutate the
965 // solver state. Keep this adjacent to trace materialization so both observe
966 // the model returned by the solver check above.
967 if (options.debug) {
968 if (traceEmissionOp)
969 rewriter.setInsertionPointAfter(traceEmissionOp);
970 else
971 rewriter.setInsertionPointToStart(satIfOp.thenBlock());
972 auto model = buildPtrAPICall(rewriter, op.getLoc(), "Z3_solver_get_model",
973 {solver});
974 auto modelStringPtr =
975 buildPtrAPICall(rewriter, op.getLoc(), "Z3_model_to_string", {model});
976 auto modelFormatString =
977 buildString(rewriter, op.getLoc(), getHeaderString("Model"));
978 buildCall(rewriter, op.getLoc(), "printf", printfType,
979 {modelFormatString, modelStringPtr});
980 }
981
982 // Otherwise, the 'else' block checks if the assertions are unsatisfiable or
983 // unknown. The corresponding regions can also be simply inlined into the
984 // two branches of this nested if-statement as well.
985 rewriter.createBlock(&satIfOp.getElseRegion());
986 Value constNegOne =
987 LLVM::ConstantOp::create(rewriter, loc, checkResult.getType(), -1);
988 Value isUnsat = LLVM::ICmpOp::create(rewriter, loc, LLVM::ICmpPredicate::eq,
989 checkResult, constNegOne);
990 auto unsatIfOp = scf::IfOp::create(rewriter, loc, resultTypes, isUnsat);
991 scf::YieldOp::create(rewriter, loc, unsatIfOp->getResults());
992
993 rewriter.inlineRegionBefore(op.getUnsatRegion(), unsatIfOp.getThenRegion(),
994 unsatIfOp.getThenRegion().end());
995 rewriter.inlineRegionBefore(op.getUnknownRegion(),
996 unsatIfOp.getElseRegion(),
997 unsatIfOp.getElseRegion().end());
998
999 rewriter.replaceOp(op, satIfOp->getResults());
1000
1001 if (options.debug) {
1002 // In debug-mode, if the assertions are unsatisfiable we can print the
1003 // proof.
1004 rewriter.setInsertionPointToStart(unsatIfOp.thenBlock());
1005 auto proof = buildPtrAPICall(rewriter, op.getLoc(), "Z3_solver_get_proof",
1006 {solver});
1007 auto stringPtr =
1008 buildPtrAPICall(rewriter, op.getLoc(), "Z3_ast_to_string", {proof});
1009 auto formatString =
1010 buildString(rewriter, op.getLoc(), getHeaderString("Proof"));
1011 buildCall(rewriter, op.getLoc(), "printf", printfType,
1012 {formatString, stringPtr});
1013 }
1014
1015 return success();
1016 }
1017};
1018
1019/// Lower `smt.forall` and `smt.exists` operations to the following Z3 API call.
1020/// ```
1021/// Z3_ast Z3_API Z3_mk_{forall|exists}_const(
1022/// Z3_context c,
1023/// unsigned weight,
1024/// unsigned num_bound,
1025/// Z3_app const bound[],
1026/// unsigned num_patterns,
1027/// Z3_pattern const patterns[],
1028/// Z3_ast body
1029/// );
1030/// ```
1031/// All nested regions are inlined into the parent region and the block
1032/// arguments are replaced with new `smt.declare_fun` constants that are also
1033/// passed to the `bound` argument of above API function. Patterns are created
1034/// with the following API function.
1035/// ```
1036/// Z3_pattern Z3_API Z3_mk_pattern(Z3_context c, unsigned num_patterns,
1037/// Z3_ast const terms[]);
1038/// ```
1039/// Where each operand of the `smt.yield` in a pattern region is a 'term'.
1040template <typename QuantifierOp>
1041struct QuantifierLowering : public SMTLoweringPattern<QuantifierOp> {
1042 using SMTLoweringPattern<QuantifierOp>::SMTLoweringPattern;
1043 using SMTLoweringPattern<QuantifierOp>::typeConverter;
1044 using SMTLoweringPattern<QuantifierOp>::buildPtrAPICall;
1045 using OpAdaptor = typename QuantifierOp::Adaptor;
1046
1047 Value createStorageForValueList(ValueRange values, Location loc,
1048 ConversionPatternRewriter &rewriter) const {
1049 Type ptrTy = LLVM::LLVMPointerType::get(rewriter.getContext());
1050 Type arrTy = LLVM::LLVMArrayType::get(ptrTy, values.size());
1051 Value constOne =
1052 LLVM::ConstantOp::create(rewriter, loc, rewriter.getI32Type(), 1);
1053 Value storage =
1054 LLVM::AllocaOp::create(rewriter, loc, ptrTy, arrTy, constOne);
1055 Value array = LLVM::UndefOp::create(rewriter, loc, arrTy);
1056
1057 for (auto [i, val] : llvm::enumerate(values))
1058 array = LLVM::InsertValueOp::create(rewriter, loc, array, val,
1059 ArrayRef<int64_t>(i));
1060
1061 LLVM::StoreOp::create(rewriter, loc, array, storage);
1062
1063 return storage;
1064 }
1065
1066 LogicalResult
1067 matchAndRewrite(QuantifierOp op, OpAdaptor adaptor,
1068 ConversionPatternRewriter &rewriter) const final {
1069 Location loc = op.getLoc();
1070 Type ptrTy = LLVM::LLVMPointerType::get(rewriter.getContext());
1071
1072 // no-pattern attribute not supported yet because the Z3 CAPI allows more
1073 // fine-grained control where a list of patterns to be banned can be given.
1074 // This means, the no-pattern attribute is equivalent to providing a list of
1075 // all possible sub-expressions in the quantifier body to the CAPI.
1076 if (adaptor.getNoPattern())
1077 return rewriter.notifyMatchFailure(
1078 op, "no-pattern attribute not yet supported!");
1079
1080 rewriter.setInsertionPoint(op);
1081
1082 // Weight attribute
1083 Value weight = LLVM::ConstantOp::create(
1084 rewriter, loc, rewriter.getI32Type(), adaptor.getWeight());
1085
1086 // Bound variables
1087 unsigned numDecls = op.getBody().getNumArguments();
1088 Value numDeclsVal = LLVM::ConstantOp::create(
1089 rewriter, loc, rewriter.getI32Type(), numDecls);
1090
1091 // We replace the block arguments with constant symbolic values and inform
1092 // the quantifier API call which constants it should treat as bound
1093 // variables. We also need to make sure that we use the exact same SSA
1094 // values in the pattern regions since we lower constant declaration
1095 // operation to always produce fresh constants.
1096 SmallVector<Value> repl;
1097 for (auto [i, arg] : llvm::enumerate(op.getBody().getArguments())) {
1098 Value newArg;
1099 if (adaptor.getBoundVarNames().has_value())
1100 newArg = smt::DeclareFunOp::create(
1101 rewriter, loc, arg.getType(),
1102 cast<StringAttr>((*adaptor.getBoundVarNames())[i]));
1103 else
1104 newArg = smt::DeclareFunOp::create(rewriter, loc, arg.getType());
1105 repl.push_back(typeConverter->materializeTargetConversion(
1106 rewriter, loc, typeConverter->convertType(arg.getType()), newArg));
1107 }
1108
1109 Value boundStorage = createStorageForValueList(repl, loc, rewriter);
1110
1111 // Body Expression
1112 auto yieldOp = cast<smt::YieldOp>(op.getBody().front().getTerminator());
1113 Value bodyExp = yieldOp.getValues()[0];
1114 rewriter.setInsertionPointAfterValue(bodyExp);
1115 bodyExp = typeConverter->materializeTargetConversion(
1116 rewriter, loc, typeConverter->convertType(bodyExp.getType()), bodyExp);
1117 rewriter.eraseOp(yieldOp);
1118
1119 rewriter.inlineBlockBefore(&op.getBody().front(), op, repl);
1120 rewriter.setInsertionPoint(op);
1121
1122 // Patterns
1123 unsigned numPatterns = adaptor.getPatterns().size();
1124 Value numPatternsVal = LLVM::ConstantOp::create(
1125 rewriter, loc, rewriter.getI32Type(), numPatterns);
1126
1127 Value patternStorage;
1128 if (numPatterns > 0) {
1129 SmallVector<Value> patterns;
1130 for (Region *patternRegion : adaptor.getPatterns()) {
1131 auto yieldOp =
1132 cast<smt::YieldOp>(patternRegion->front().getTerminator());
1133 auto patternTerms = yieldOp.getOperands();
1134
1135 rewriter.setInsertionPoint(yieldOp);
1136 SmallVector<Value> patternList;
1137 for (auto val : patternTerms)
1138 patternList.push_back(typeConverter->materializeTargetConversion(
1139 rewriter, loc, typeConverter->convertType(val.getType()), val));
1140
1141 rewriter.eraseOp(yieldOp);
1142 rewriter.inlineBlockBefore(&patternRegion->front(), op, repl);
1143
1144 rewriter.setInsertionPoint(op);
1145 Value numTerms = LLVM::ConstantOp::create(
1146 rewriter, loc, rewriter.getI32Type(), patternTerms.size());
1147 Value patternTermStorage =
1148 createStorageForValueList(patternList, loc, rewriter);
1149 Value pattern = buildPtrAPICall(rewriter, loc, "Z3_mk_pattern",
1150 {numTerms, patternTermStorage});
1151
1152 patterns.emplace_back(pattern);
1153 }
1154 patternStorage = createStorageForValueList(patterns, loc, rewriter);
1155 } else {
1156 // If we set the num_patterns parameter to 0, we can just pass a nullptr
1157 // as storage.
1158 patternStorage = LLVM::ZeroOp::create(rewriter, loc, ptrTy);
1159 }
1160
1161 StringRef apiCallName = "Z3_mk_forall_const";
1162 if (std::is_same_v<QuantifierOp, ExistsOp>)
1163 apiCallName = "Z3_mk_exists_const";
1164 Value quantifierExp =
1165 buildPtrAPICall(rewriter, loc, apiCallName,
1166 {weight, numDeclsVal, boundStorage, numPatternsVal,
1167 patternStorage, bodyExp});
1168
1169 rewriter.replaceOp(op, quantifierExp);
1170 return success();
1171 }
1172};
1173
1174/// Lower `smt.bv.repeat` operations to Z3 API function calls of the form
1175/// ```
1176/// Z3_ast Z3_API Z3_mk_repeat(Z3_context c, unsigned i, Z3_ast t1);
1177/// ```
1178struct RepeatOpLowering : public SMTLoweringPattern<RepeatOp> {
1179 using SMTLoweringPattern::SMTLoweringPattern;
1180
1181 LogicalResult
1182 matchAndRewrite(RepeatOp op, OpAdaptor adaptor,
1183 ConversionPatternRewriter &rewriter) const final {
1184 Value count = LLVM::ConstantOp::create(
1185 rewriter, op.getLoc(), rewriter.getI32Type(), op.getCount());
1186 rewriter.replaceOp(op,
1187 buildPtrAPICall(rewriter, op.getLoc(), "Z3_mk_repeat",
1188 {count, adaptor.getInput()}));
1189 return success();
1190 }
1191};
1192
1193/// Lower `smt.bv.extract` operations to Z3 API function calls of the following
1194/// form, where the output bit-vector has size `n = high - low + 1`. This means,
1195/// both the 'high' and 'low' indices are inclusive.
1196/// ```
1197/// Z3_ast Z3_API Z3_mk_extract(Z3_context c, unsigned high, unsigned low,
1198/// Z3_ast t1);
1199/// ```
1200struct ExtractOpLowering : public SMTLoweringPattern<ExtractOp> {
1201 using SMTLoweringPattern::SMTLoweringPattern;
1202
1203 LogicalResult
1204 matchAndRewrite(ExtractOp op, OpAdaptor adaptor,
1205 ConversionPatternRewriter &rewriter) const final {
1206 Location loc = op.getLoc();
1207 Value low = LLVM::ConstantOp::create(rewriter, loc, rewriter.getI32Type(),
1208 adaptor.getLowBit());
1209 Value high = LLVM::ConstantOp::create(rewriter, loc, rewriter.getI32Type(),
1210 adaptor.getLowBit() +
1211 op.getType().getWidth() - 1);
1212 rewriter.replaceOp(op, buildPtrAPICall(rewriter, loc, "Z3_mk_extract",
1213 {high, low, adaptor.getInput()}));
1214 return success();
1215 }
1216};
1217
1218/// Lower `smt.array.broadcast` operations to Z3 API function calls of the form
1219/// ```
1220/// Z3_ast Z3_API Z3_mk_const_array(Z3_context c, Z3_sort domain, Z3_ast v);
1221/// ```
1222struct ArrayBroadcastOpLowering
1223 : public SMTLoweringPattern<smt::ArrayBroadcastOp> {
1224 using SMTLoweringPattern::SMTLoweringPattern;
1225
1226 LogicalResult
1227 matchAndRewrite(smt::ArrayBroadcastOp op, OpAdaptor adaptor,
1228 ConversionPatternRewriter &rewriter) const final {
1229 auto domainSort = buildSort(
1230 rewriter, op.getLoc(),
1231 cast<smt::ArrayType>(op.getResult().getType()).getDomainType());
1232
1233 rewriter.replaceOp(op, buildPtrAPICall(rewriter, op.getLoc(),
1234 "Z3_mk_const_array",
1235 {domainSort, adaptor.getValue()}));
1236 return success();
1237 }
1238};
1239
1240/// Lower the `smt.constant` operation to one of the following Z3 API function
1241/// calls depending on the value of the boolean attribute.
1242/// ```
1243/// Z3_ast Z3_API Z3_mk_true(Z3_context c);
1244/// Z3_ast Z3_API Z3_mk_false(Z3_context c);
1245/// ```
1246struct BoolConstantOpLowering : public SMTLoweringPattern<smt::BoolConstantOp> {
1247 using SMTLoweringPattern::SMTLoweringPattern;
1248
1249 LogicalResult
1250 matchAndRewrite(smt::BoolConstantOp op, OpAdaptor adaptor,
1251 ConversionPatternRewriter &rewriter) const final {
1252 rewriter.replaceOp(
1253 op, buildPtrAPICall(rewriter, op.getLoc(),
1254 adaptor.getValue() ? "Z3_mk_true" : "Z3_mk_false"));
1255 return success();
1256 }
1257};
1258
1259/// Lower `smt.int.constant` operations to one of the following two Z3 API
1260/// function calls depending on whether the storage APInt has a bit-width that
1261/// fits in a `uint64_t`.
1262/// ```
1263/// Z3_sort Z3_API Z3_mk_int_sort(Z3_context c);
1264///
1265/// Z3_ast Z3_API Z3_mk_int64(Z3_context c, int64_t v, Z3_sort ty);
1266///
1267/// Z3_ast Z3_API Z3_mk_numeral(Z3_context c, Z3_string numeral, Z3_sort ty);
1268/// Z3_ast Z3_API Z3_mk_unary_minus(Z3_context c, Z3_ast arg);
1269/// ```
1270struct IntConstantOpLowering : public SMTLoweringPattern<smt::IntConstantOp> {
1271 using SMTLoweringPattern::SMTLoweringPattern;
1272
1273 LogicalResult
1274 matchAndRewrite(smt::IntConstantOp op, OpAdaptor adaptor,
1275 ConversionPatternRewriter &rewriter) const final {
1276 Location loc = op.getLoc();
1277 Value type = buildPtrAPICall(rewriter, loc, "Z3_mk_int_sort");
1278 if (adaptor.getValue().getBitWidth() <= 64) {
1279 Value val = LLVM::ConstantOp::create(rewriter, loc, rewriter.getI64Type(),
1280 adaptor.getValue().getSExtValue());
1281 rewriter.replaceOp(
1282 op, buildPtrAPICall(rewriter, loc, "Z3_mk_int64", {val, type}));
1283 return success();
1284 }
1285
1286 std::string numeralStr;
1287 llvm::raw_string_ostream stream(numeralStr);
1288 stream << adaptor.getValue().abs();
1289
1290 Value numeral = buildString(rewriter, loc, numeralStr);
1291 Value intNumeral =
1292 buildPtrAPICall(rewriter, loc, "Z3_mk_numeral", {numeral, type});
1293
1294 if (adaptor.getValue().isNegative())
1295 intNumeral =
1296 buildPtrAPICall(rewriter, loc, "Z3_mk_unary_minus", intNumeral);
1297
1298 rewriter.replaceOp(op, intNumeral);
1299 return success();
1300 }
1301};
1302
1303/// Lower `smt.int.cmp` operations to one of the following Z3 API function calls
1304/// depending on the predicate.
1305/// ```
1306/// Z3_ast Z3_API Z3_mk_{{pred}}(Z3_context c, Z3_ast t1, Z3_ast t2);
1307/// ```
1308struct IntCmpOpLowering : public SMTLoweringPattern<IntCmpOp> {
1309 using SMTLoweringPattern::SMTLoweringPattern;
1310
1311 LogicalResult
1312 matchAndRewrite(IntCmpOp op, OpAdaptor adaptor,
1313 ConversionPatternRewriter &rewriter) const final {
1314 rewriter.replaceOp(
1315 op,
1316 buildPtrAPICall(rewriter, op.getLoc(),
1317 "Z3_mk_" + stringifyIntPredicate(op.getPred()).str(),
1318 {adaptor.getLhs(), adaptor.getRhs()}));
1319 return success();
1320 }
1321};
1322
1323/// Lower `smt.int2bv` operations to the following Z3 API function calls.
1324/// ```
1325/// Z3_ast Z3_API Z3_mk_int2bv(Z3_context c, unsigned n, Z3_ast t1);
1326/// ```
1327struct Int2BVOpLowering : public SMTLoweringPattern<Int2BVOp> {
1328 using SMTLoweringPattern::SMTLoweringPattern;
1329
1330 LogicalResult
1331 matchAndRewrite(Int2BVOp op, OpAdaptor adaptor,
1332 ConversionPatternRewriter &rewriter) const final {
1333 Value widthConst =
1334 LLVM::ConstantOp::create(rewriter, op->getLoc(), rewriter.getI32Type(),
1335 op.getResult().getType().getWidth());
1336 rewriter.replaceOp(op,
1337 buildPtrAPICall(rewriter, op.getLoc(), "Z3_mk_int2bv",
1338 {widthConst, adaptor.getInput()}));
1339 return success();
1340 }
1341};
1342
1343/// Lower `smt.bv2int` operations to the following Z3 API function call.
1344/// ```
1345/// Z3_ast Z3_API Z3_mk_bv2int(Z3_context c, Z3_ast t1, bool is_signed)
1346/// ```
1347struct BV2IntOpLowering : public SMTLoweringPattern<BV2IntOp> {
1348 using SMTLoweringPattern::SMTLoweringPattern;
1349
1350 LogicalResult
1351 matchAndRewrite(BV2IntOp op, OpAdaptor adaptor,
1352 ConversionPatternRewriter &rewriter) const final {
1353 // FIXME: ideally we don't want to use i1 here, since bools can sometimes be
1354 // compiled to wider widths in LLVM
1355 Value isSignedConst = LLVM::ConstantOp::create(
1356 rewriter, op->getLoc(), rewriter.getI1Type(), op.getIsSigned());
1357 rewriter.replaceOp(op,
1358 buildPtrAPICall(rewriter, op.getLoc(), "Z3_mk_bv2int",
1359 {adaptor.getInput(), isSignedConst}));
1360 return success();
1361 }
1362};
1363
1364/// Lower `smt.bv.cmp` operations to one of the following Z3 API function calls,
1365/// performing two's complement comparison, depending on the predicate
1366/// attribute.
1367/// ```
1368/// Z3_ast Z3_API Z3_mk_bv{{pred}}(Z3_context c, Z3_ast t1, Z3_ast t2);
1369/// ```
1370struct BVCmpOpLowering : public SMTLoweringPattern<BVCmpOp> {
1371 using SMTLoweringPattern::SMTLoweringPattern;
1372
1373 LogicalResult
1374 matchAndRewrite(BVCmpOp op, OpAdaptor adaptor,
1375 ConversionPatternRewriter &rewriter) const final {
1376 rewriter.replaceOp(
1377 op, buildPtrAPICall(rewriter, op.getLoc(),
1378 "Z3_mk_bv" +
1379 stringifyBVCmpPredicate(op.getPred()).str(),
1380 {adaptor.getLhs(), adaptor.getRhs()}));
1381 return success();
1382 }
1383};
1384
1385/// Expand the `smt.int.abs` operation to a `smt.ite` operation.
1386struct IntAbsOpLowering : public SMTLoweringPattern<IntAbsOp> {
1387 using SMTLoweringPattern::SMTLoweringPattern;
1388
1389 LogicalResult
1390 matchAndRewrite(IntAbsOp op, OpAdaptor adaptor,
1391 ConversionPatternRewriter &rewriter) const final {
1392 Location loc = op.getLoc();
1393 Value zero = IntConstantOp::create(
1394 rewriter, loc, rewriter.getIntegerAttr(rewriter.getI1Type(), 0));
1395 Value cmp = IntCmpOp::create(rewriter, loc, IntPredicate::lt,
1396 adaptor.getInput(), zero);
1397 Value neg = IntSubOp::create(rewriter, loc, zero, adaptor.getInput());
1398 rewriter.replaceOpWithNewOp<IteOp>(op, cmp, neg, adaptor.getInput());
1399 return success();
1400 }
1401};
1402
1403//===----------------------------------------------------------------------===//
1404// Placeholder Debug Patterns
1405//===----------------------------------------------------------------------===//
1406// For now we want to ignore Debug variable and scope ops - eventually we'll
1407// give this debug info to Z3
1408
1409/// Lower bit-vector verif.bmc.trace ops to the circt-bmc runtime callback.
1410/// Other SMT values are discarded until their trace materialization is
1411/// supported.
1412struct BMCTraceLowering : public SMTLoweringPattern<verif::BMCTraceOp> {
1413 using SMTLoweringPattern::SMTLoweringPattern;
1414
1415 LogicalResult
1416 matchAndRewrite(verif::BMCTraceOp op, OpAdaptor adaptor,
1417 ConversionPatternRewriter &rewriter) const final {
1418 auto bitVectorType = dyn_cast<smt::BitVectorType>(op.getValue().getType());
1419 if (!bitVectorType) {
1420 rewriter.eraseOp(op);
1421 return success();
1422 }
1423
1424 Location loc = op.getLoc();
1425 Value name = buildString(rewriter, loc, op.getName());
1426 Value width = LLVM::ConstantOp::create(rewriter, loc, rewriter.getI32Type(),
1427 bitVectorType.getWidth());
1428 auto function = op->getParentOfType<FunctionOpInterface>();
1429 if (!function || function.getNumArguments() == 0)
1430 return rewriter.notifyMatchFailure(op, "missing BMC trace context");
1431 auto functionName =
1432 function->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName());
1433 unsigned traceArgumentOffset =
1434 functionName &&
1435 globals.traceEmissionFunctionNames.contains(functionName)
1436 ? 2
1437 : 1;
1438 if (function.getNumArguments() < traceArgumentOffset)
1439 return rewriter.notifyMatchFailure(op, "missing BMC trace context");
1440 Value traceContext =
1441 function.getArgument(function.getNumArguments() - traceArgumentOffset);
1442 if (!isa<LLVM::LLVMPointerType>(traceContext.getType()))
1443 return rewriter.notifyMatchFailure(op, "invalid BMC trace context type");
1444 auto voidType = LLVM::LLVMVoidType::get(rewriter.getContext());
1445 buildCall(
1446 rewriter, loc, "circt_bmc_record_trace",
1447 LLVM::LLVMFunctionType::get(voidType, {traceContext.getType(),
1448 adaptor.getStep().getType(),
1449 name.getType(), width.getType(),
1450 adaptor.getValue().getType()}),
1451 {traceContext, adaptor.getStep(), name, width, adaptor.getValue()});
1452 rewriter.eraseOp(op);
1453 return success();
1454 }
1455};
1456
1457/// Strip dbg.variable ops.
1458struct DbgVariableLowering : public OpConversionPattern<debug::VariableOp> {
1459 using OpConversionPattern::OpConversionPattern;
1460
1461 LogicalResult
1462 matchAndRewrite(debug::VariableOp op, OpAdaptor adaptor,
1463 ConversionPatternRewriter &rewriter) const final {
1464 rewriter.eraseOp(op);
1465 return success();
1466 }
1467};
1468
1469/// Strip dbg.scope ops.
1470struct DbgScopeLowering : public OpConversionPattern<debug::ScopeOp> {
1471 using OpConversionPattern::OpConversionPattern;
1472
1473 LogicalResult
1474 matchAndRewrite(debug::ScopeOp op, OpAdaptor adaptor,
1475 ConversionPatternRewriter &rewriter) const final {
1476 // Make sure scope's only users are variables and therefore being deleted
1477 if (llvm::any_of(op->getUsers(), [](Operation *user) {
1478 return !isa<debug::VariableOp>(user);
1479 }))
1480 return failure();
1481 rewriter.eraseOp(op);
1482 return success();
1483 }
1484};
1485
1486} // namespace
1487
1488//===----------------------------------------------------------------------===//
1489// Pass Implementation
1490//===----------------------------------------------------------------------===//
1491
1492namespace {
1493struct LowerSMTToZ3LLVMPass
1494 : public circt::impl::LowerSMTToZ3LLVMBase<LowerSMTToZ3LLVMPass> {
1495 using Base::Base;
1496 void runOnOperation() override;
1497};
1498} // namespace
1499
1500void circt::populateSMTToZ3LLVMTypeConverter(TypeConverter &converter) {
1501 converter.addConversion([](smt::BoolType type) {
1502 return LLVM::LLVMPointerType::get(type.getContext());
1503 });
1504 converter.addConversion([](smt::BitVectorType type) {
1505 return LLVM::LLVMPointerType::get(type.getContext());
1506 });
1507 converter.addConversion([](smt::ArrayType type) {
1508 return LLVM::LLVMPointerType::get(type.getContext());
1509 });
1510 converter.addConversion([](smt::IntType type) {
1511 return LLVM::LLVMPointerType::get(type.getContext());
1512 });
1513 converter.addConversion([](smt::SMTFuncType type) {
1514 return LLVM::LLVMPointerType::get(type.getContext());
1515 });
1516 converter.addConversion([](smt::SortType type) {
1517 return LLVM::LLVMPointerType::get(type.getContext());
1518 });
1519}
1520
1522 RewritePatternSet &patterns, TypeConverter &converter,
1523 SMTGlobalsHandler &globals, const LowerSMTToZ3LLVMOptions &options) {
1524#define ADD_VARIADIC_PATTERN(OP, APINAME, MIN_NUM_ARGS) \
1525 patterns.add<VariadicSMTPattern<OP>>(/*NOLINT(bugprone-macro-parentheses)*/ \
1526 converter, patterns.getContext(), \
1527 globals, options, APINAME, \
1528 MIN_NUM_ARGS);
1529
1530#define ADD_ONE_TO_ONE_PATTERN(OP, APINAME, NUM_ARGS) \
1531 patterns.add<OneToOneSMTPattern<OP>>(/*NOLINT(bugprone-macro-parentheses)*/ \
1532 converter, patterns.getContext(), \
1533 globals, options, APINAME, NUM_ARGS);
1534
1535 // Lower `smt.distinct` operations which allows a variadic number of operands
1536 // according to the `:pairwise` attribute. The Z3 API function supports a
1537 // variadic number of operands as well, i.e., a direct lowering is possible:
1538 // ```
1539 // Z3_ast Z3_API Z3_mk_distinct(Z3_context c, unsigned num_args, Z3_ast const
1540 // args[])
1541 // ```
1542 // The API function requires num_args > 1 which is guaranteed to be satisfied
1543 // because `smt.distinct` is verified to have > 1 operands.
1544 ADD_VARIADIC_PATTERN(DistinctOp, "Z3_mk_distinct", 2);
1545
1546 // Lower `smt.and` operations which allows a variadic number of operands
1547 // according to the `:left-assoc` attribute. The Z3 API function supports a
1548 // variadic number of operands as well, i.e., a direct lowering is possible:
1549 // ```
1550 // Z3_ast Z3_API Z3_mk_and(Z3_context c, unsigned num_args, Z3_ast const
1551 // args[])
1552 // ```
1553 // The API function requires num_args > 1. This is not guaranteed by the
1554 // `smt.and` operation and thus the pattern will not apply when no operand is
1555 // present. The constant folder of the operation is assumed to fold this to
1556 // a constant 'true' (neutral element of AND).
1557 ADD_VARIADIC_PATTERN(AndOp, "Z3_mk_and", 2);
1558
1559 // Lower `smt.or` operations which allows a variadic number of operands
1560 // according to the `:left-assoc` attribute. The Z3 API function supports a
1561 // variadic number of operands as well, i.e., a direct lowering is possible:
1562 // ```
1563 // Z3_ast Z3_API Z3_mk_or(Z3_context c, unsigned num_args, Z3_ast const
1564 // args[])
1565 // ```
1566 // The API function requires num_args > 1. This is not guaranteed by the
1567 // `smt.or` operation and thus the pattern will not apply when no operand is
1568 // present. The constant folder of the operation is assumed to fold this to
1569 // a constant 'false' (neutral element of OR).
1570 ADD_VARIADIC_PATTERN(OrOp, "Z3_mk_or", 2);
1571
1572 // Lower `smt.not` operations to the following Z3 API function:
1573 // ```
1574 // Z3_ast Z3_API Z3_mk_not(Z3_context c, Z3_ast a);
1575 // ```
1576 ADD_ONE_TO_ONE_PATTERN(NotOp, "Z3_mk_not", 1);
1577
1578 // Lower `smt.xor` operations which allows a variadic number of operands
1579 // according to the `:left-assoc` attribute. The Z3 API function, however,
1580 // only takes two operands.
1581 // ```
1582 // Z3_ast Z3_API Z3_mk_xor(Z3_context c, Z3_ast t1, Z3_ast t2);
1583 // ```
1584 // Therefore, we need to decompose the operation first to a sequence of XOR
1585 // operations matching the left associative behavior.
1586 patterns.add<LowerLeftAssocSMTPattern<XOrOp>>(
1587 converter, patterns.getContext(), globals, options);
1588 ADD_ONE_TO_ONE_PATTERN(XOrOp, "Z3_mk_xor", 2);
1589
1590 // Lower `smt.implies` operations to the following Z3 API function:
1591 // ```
1592 // Z3_ast Z3_API Z3_mk_implies(Z3_context c, Z3_ast t1, Z3_ast t2);
1593 // ```
1594 ADD_ONE_TO_ONE_PATTERN(ImpliesOp, "Z3_mk_implies", 2);
1595
1596 // All the bit-vector arithmetic and bitwise operations conveniently lower to
1597 // Z3 API function calls with essentially matching names and a one-to-one
1598 // correspondence of operands to call arguments.
1599 ADD_ONE_TO_ONE_PATTERN(BVNegOp, "Z3_mk_bvneg", 1);
1600 ADD_ONE_TO_ONE_PATTERN(BVAddOp, "Z3_mk_bvadd", 2);
1601 ADD_ONE_TO_ONE_PATTERN(BVMulOp, "Z3_mk_bvmul", 2);
1602 ADD_ONE_TO_ONE_PATTERN(BVURemOp, "Z3_mk_bvurem", 2);
1603 ADD_ONE_TO_ONE_PATTERN(BVSRemOp, "Z3_mk_bvsrem", 2);
1604 ADD_ONE_TO_ONE_PATTERN(BVSModOp, "Z3_mk_bvsmod", 2);
1605 ADD_ONE_TO_ONE_PATTERN(BVUDivOp, "Z3_mk_bvudiv", 2);
1606 ADD_ONE_TO_ONE_PATTERN(BVSDivOp, "Z3_mk_bvsdiv", 2);
1607 ADD_ONE_TO_ONE_PATTERN(BVShlOp, "Z3_mk_bvshl", 2);
1608 ADD_ONE_TO_ONE_PATTERN(BVLShrOp, "Z3_mk_bvlshr", 2);
1609 ADD_ONE_TO_ONE_PATTERN(BVAShrOp, "Z3_mk_bvashr", 2);
1610 ADD_ONE_TO_ONE_PATTERN(BVNotOp, "Z3_mk_bvnot", 1);
1611 ADD_ONE_TO_ONE_PATTERN(BVAndOp, "Z3_mk_bvand", 2);
1612 ADD_ONE_TO_ONE_PATTERN(BVOrOp, "Z3_mk_bvor", 2);
1613 ADD_ONE_TO_ONE_PATTERN(BVXOrOp, "Z3_mk_bvxor", 2);
1614
1615 // The `smt.bv.concat` operation only supports two operands, just like the
1616 // Z3 API function.
1617 // ```
1618 // Z3_ast Z3_API Z3_mk_concat(Z3_context c, Z3_ast t1, Z3_ast t2);
1619 // ```
1620 ADD_ONE_TO_ONE_PATTERN(ConcatOp, "Z3_mk_concat", 2);
1621
1622 // Lower the `smt.ite` operation to the following Z3 API function call, where
1623 // `t1` must have boolean sort.
1624 // ```
1625 // Z3_ast Z3_API Z3_mk_ite(Z3_context c, Z3_ast t1, Z3_ast t2, Z3_ast t3);
1626 // ```
1627 ADD_ONE_TO_ONE_PATTERN(IteOp, "Z3_mk_ite", 3);
1628
1629 // Lower the `smt.array.select` operation to the following Z3 function call.
1630 // The operand declaration of the operation matches the order of arguments of
1631 // the API function.
1632 // ```
1633 // Z3_ast Z3_API Z3_mk_select(Z3_context c, Z3_ast a, Z3_ast i);
1634 // ```
1635 // Where `a` is the array expression and `i` is the index expression.
1636 ADD_ONE_TO_ONE_PATTERN(ArraySelectOp, "Z3_mk_select", 2);
1637
1638 // Lower the `smt.array.store` operation to the following Z3 function call.
1639 // The operand declaration of the operation matches the order of arguments of
1640 // the API function.
1641 // ```
1642 // Z3_ast Z3_API Z3_mk_store(Z3_context c, Z3_ast a, Z3_ast i, Z3_ast v);
1643 // ```
1644 // Where `a` is the array expression, `i` is the index expression, and `v` is
1645 // the value expression to be stored.
1646 ADD_ONE_TO_ONE_PATTERN(ArrayStoreOp, "Z3_mk_store", 3);
1647
1648 // Lower the `smt.int.add` operation to the following Z3 API function call.
1649 // ```
1650 // Z3_ast Z3_API Z3_mk_add(Z3_context c, unsigned num_args, Z3_ast const
1651 // args[]);
1652 // ```
1653 // The number of arguments must be greater than zero. Therefore, the pattern
1654 // will fail if applied to an operation with less than two operands.
1655 ADD_VARIADIC_PATTERN(IntAddOp, "Z3_mk_add", 2);
1656
1657 // Lower the `smt.int.mul` operation to the following Z3 API function call.
1658 // ```
1659 // Z3_ast Z3_API Z3_mk_mul(Z3_context c, unsigned num_args, Z3_ast const
1660 // args[]);
1661 // ```
1662 // The number of arguments must be greater than zero. Therefore, the pattern
1663 // will fail if applied to an operation with less than two operands.
1664 ADD_VARIADIC_PATTERN(IntMulOp, "Z3_mk_mul", 2);
1665
1666 // Lower the `smt.int.sub` operation to the following Z3 API function call.
1667 // ```
1668 // Z3_ast Z3_API Z3_mk_sub(Z3_context c, unsigned num_args, Z3_ast const
1669 // args[]);
1670 // ```
1671 // The number of arguments must be greater than zero. Since the `smt.int.sub`
1672 // operation always has exactly two operands, this trivially holds.
1673 ADD_VARIADIC_PATTERN(IntSubOp, "Z3_mk_sub", 2);
1674
1675 // Lower the `smt.int.div` operation to the following Z3 API function call.
1676 // ```
1677 // Z3_ast Z3_API Z3_mk_div(Z3_context c, Z3_ast arg1, Z3_ast arg2);
1678 // ```
1679 ADD_ONE_TO_ONE_PATTERN(IntDivOp, "Z3_mk_div", 2);
1680
1681 // Lower the `smt.int.mod` operation to the following Z3 API function call.
1682 // ```
1683 // Z3_ast Z3_API Z3_mk_mod(Z3_context c, Z3_ast arg1, Z3_ast arg2);
1684 // ```
1685 ADD_ONE_TO_ONE_PATTERN(IntModOp, "Z3_mk_mod", 2);
1686
1687#undef ADD_VARIADIC_PATTERN
1688#undef ADD_ONE_TO_ONE_PATTERN
1689
1690 // Lower `smt.eq` operations which allows a variadic number of operands
1691 // according to the `:chainable` attribute. The Z3 API function does not
1692 // support a variadic number of operands, but exactly two:
1693 // ```
1694 // Z3_ast Z3_API Z3_mk_eq(Z3_context c, Z3_ast l, Z3_ast r)
1695 // ```
1696 // As a result, we first apply a rewrite pattern that unfolds chainable
1697 // operators and then lower it one-to-one to the API function. In this case,
1698 // this means:
1699 // ```
1700 // eq(a,b,c,d) ->
1701 // and(eq(a,b), eq(b,c), eq(c,d)) ->
1702 // and(Z3_mk_eq(ctx, a, b), Z3_mk_eq(ctx, b, c), Z3_mk_eq(ctx, c, d))
1703 // ```
1704 // The patterns for `smt.and` will then do the remaining work.
1705 patterns.add<LowerChainableSMTPattern<EqOp>>(converter, patterns.getContext(),
1706 globals, options);
1707 patterns.add<OneToOneSMTPattern<EqOp>>(converter, patterns.getContext(),
1708 globals, options, "Z3_mk_eq", 2);
1709
1710 // Other lowering patterns. Refer to their implementation directly for more
1711 // information.
1712 patterns.add<BVConstantOpLowering, DeclareFunOpLowering, AssertOpLowering,
1713 ResetOpLowering, PushOpLowering, PopOpLowering, CheckOpLowering,
1714 SolverOpLowering, ApplyFuncOpLowering, YieldOpLowering,
1715 RepeatOpLowering, ExtractOpLowering, BoolConstantOpLowering,
1716 IntConstantOpLowering, ArrayBroadcastOpLowering, BVCmpOpLowering,
1717 IntCmpOpLowering, IntAbsOpLowering, Int2BVOpLowering,
1718 BV2IntOpLowering, QuantifierLowering<ForallOp>,
1719 QuantifierLowering<ExistsOp>>(converter, patterns.getContext(),
1720 globals, options);
1721 patterns.add<BMCTraceLowering>(converter, patterns.getContext(), globals,
1722 options);
1723 patterns.add<DbgVariableLowering, DbgScopeLowering>(patterns.getContext());
1724}
1725
1726void LowerSMTToZ3LLVMPass::runOnOperation() {
1727 LowerSMTToZ3LLVMOptions options;
1728 options.debug = debug;
1729 options.printOnlyFirstCounterexample = printOnlyFirstCounterexample;
1730
1731 // Check that the lowering is possible
1732 // Specifically, check that the use of set-logic ops is valid for z3
1733 auto setLogicCheck = getOperation().walk([&](SolverOp solverOp)
1734 -> WalkResult {
1735 // Check that solver ops only contain one set-logic op and that they're at
1736 // the start of the body
1737 auto setLogicOps = solverOp.getBodyRegion().getOps<smt::SetLogicOp>();
1738 auto numSetLogicOps = std::distance(setLogicOps.begin(), setLogicOps.end());
1739 if (numSetLogicOps > 1) {
1740 return solverOp.emitError(
1741 "multiple set-logic operations found in one solver operation - Z3 "
1742 "only supports setting the logic once");
1743 }
1744 if (numSetLogicOps == 1)
1745 // Check the only ops before the set-logic op are ConstantLike
1746 for (auto &blockOp : solverOp.getBodyRegion().getOps()) {
1747 if (isa<smt::SetLogicOp>(blockOp))
1748 break;
1749 if (!blockOp.hasTrait<OpTrait::ConstantLike>()) {
1750 return solverOp.emitError("set-logic operation must be the first "
1751 "non-constant operation in a solver "
1752 "operation");
1753 }
1754 }
1755 return WalkResult::advance();
1756 });
1757 if (setLogicCheck.wasInterrupted())
1758 return signalPassFailure();
1759
1760 llvm::StringMap<Operation *> traceNames;
1761 auto traceNameCheck =
1762 getOperation().walk([&](verif::BMCTraceOp traceOp) -> WalkResult {
1763 auto [it, inserted] =
1764 traceNames.try_emplace(traceOp.getName(), traceOp.getOperation());
1765 if (inserted)
1766 return WalkResult::advance();
1767 auto error = traceOp.emitError() << "duplicate BMC trace name '"
1768 << traceOp.getName() << "'";
1769 error.attachNote(it->second->getLoc())
1770 << "first BMC trace with this name is here";
1771 return WalkResult::interrupt();
1772 });
1773 if (traceNameCheck.wasInterrupted())
1774 return signalPassFailure();
1775
1776 // Thread an opaque runtime context into every function containing a BMC
1777 // trace marker. The lowering below forwards this argument to the runtime
1778 // callback, making trace state explicit in the generated code.
1779 llvm::SmallPtrSet<Operation *, 4> traceFunctions;
1780 getOperation().walk([&](verif::BMCTraceOp traceOp) {
1781 auto function = traceOp->getParentOfType<FunctionOpInterface>();
1782 if (function)
1783 traceFunctions.insert(function.getOperation());
1784 });
1785 auto traceContextType = LLVM::LLVMPointerType::get(&getContext());
1786 for (Operation *operation : traceFunctions) {
1787 auto function = cast<FunctionOpInterface>(operation);
1788 if (failed(function.insertArgument(function.getNumArguments(),
1789 traceContextType, {},
1790 function.getLoc()))) {
1791 function.emitError("failed to add BMC trace context argument");
1792 return signalPassFailure();
1793 }
1794 }
1795
1796 // Set up the type converter
1797 LLVMTypeConverter converter(&getContext());
1799
1800 RewritePatternSet patterns(&getContext());
1801
1802 // Populate the func to LLVM conversion patterns for two reasons:
1803 // * Typically functions are represented using `func.func` and including the
1804 // patterns to lower them here is more convenient for most lowering
1805 // pipelines (avoids running another pass).
1806 // * Already having `llvm.func` in the input or lowering `func.func` before
1807 // the SMT in the body leads to issues because the SCF conversion patterns
1808 // don't take the type converter into consideration and thus create blocks
1809 // with the old types for block arguments. However, the conversion happens
1810 // top-down and thus are assumed to be converted by the parent function op
1811 // which at that point would have already been lowered (and the blocks are
1812 // also not there when doing everything in one pass, i.e.,
1813 // `populateAnyFunctionOpInterfaceTypeConversionPattern` does not have any
1814 // effect as well). Are the SCF lowering patterns actually broken and should
1815 // take a type-converter?
1816 populateFuncToLLVMConversionPatterns(converter, patterns);
1817 arith::populateArithToLLVMConversionPatterns(converter, patterns);
1818
1819 // Populate SCF to CF and CF to LLVM lowering patterns because we create
1820 // `scf.if` operations in the lowering patterns for convenience (given the
1821 // above issue we might want to lower to LLVM directly; or fix upstream?)
1822 populateSCFToControlFlowConversionPatterns(patterns);
1823 mlir::cf::populateControlFlowToLLVMConversionPatterns(converter, patterns);
1824
1825 // Create the globals to store the context and solver and populate the SMT
1826 // lowering patterns.
1827 OpBuilder builder(&getContext());
1828 auto globals = SMTGlobalsHandler::create(builder, getOperation());
1829 populateSMTToZ3LLVMConversionPatterns(patterns, converter, globals, options);
1830
1831 // Do a full conversion. This assumes that all other dialects have been
1832 // lowered before this pass already.
1833 LLVMConversionTarget target(getContext());
1834 target.addLegalOp<mlir::ModuleOp>();
1835 target.addLegalOp<scf::YieldOp>();
1836 target.addIllegalDialect<debug::DebugDialect>();
1837 target.addIllegalOp<verif::BMCTraceOp>();
1838
1839 if (failed(applyFullConversion(getOperation(), target, std::move(patterns))))
1840 return signalPassFailure();
1841}
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static FIRRTLBaseType convertType(FIRRTLBaseType type)
Returns null type if no conversion is needed.
Definition DropConst.cpp:32
#define ADD_VARIADIC_PATTERN(OP, APINAME, MIN_NUM_ARGS)
#define ADD_ONE_TO_ONE_PATTERN(OP, APINAME, NUM_ARGS)
static Location getLoc(DefSlot slot)
Definition Mem2Reg.cpp:222
RewritePatternSet pattern
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
StringRef newName(const Twine &name)
Return a unique name, derived from the input name, and add the new name to the internal namespace.
Definition Namespace.h:87
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
void error(Twine message)
Definition LSPUtils.cpp:16
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
void populateSMTToZ3LLVMTypeConverter(TypeConverter &converter)
Populate the given type converter with the SMT to LLVM type conversions.
void populateSMTToZ3LLVMConversionPatterns(RewritePatternSet &patterns, TypeConverter &converter, SMTGlobalsHandler &globals, const LowerSMTToZ3LLVMOptions &options)
Add the SMT to LLVM IR conversion patterns to 'patterns'.
Definition debug.py:1
A symbol cache for LLVM globals and functions relevant to SMT lowering patterns.
Definition SMTToZ3LLVM.h:26
static SMTGlobalsHandler create(OpBuilder &builder, ModuleOp module)
Creates the LLVM global operations to store the pointers to the solver and the context and returns a ...
SMTGlobalsHandler(ModuleOp module, mlir::LLVM::GlobalOp solver, mlir::LLVM::GlobalOp ctx)
Initializes the caches and keeps track of the given globals to store the pointers to the SMT solver a...