1 //== Z3ConstraintManager.cpp --------------------------------*- C++ -*--==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/Basic/TargetInfo.h"
11 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
12 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
13 #include "clang/StaticAnalyzer/Core/PathSensitive/SMTConstraintManager.h"
14 #include "clang/StaticAnalyzer/Core/PathSensitive/SMTContext.h"
15 #include "clang/StaticAnalyzer/Core/PathSensitive/SMTExpr.h"
16 #include "clang/StaticAnalyzer/Core/PathSensitive/SMTSolver.h"
17 #include "clang/StaticAnalyzer/Core/PathSensitive/SMTSort.h"
19 #include "clang/Config/config.h"
21 using namespace clang;
24 #if CLANG_ANALYZER_WITH_Z3
30 /// Configuration class for Z3
32 friend class Z3Context;
37 Z3Config() : Config(Z3_mk_config()) {
38 // Enable model finding
39 Z3_set_param_value(Config, "model", "true");
40 // Disable proof generation
41 Z3_set_param_value(Config, "proof", "false");
42 // Set timeout to 15000ms = 15s
43 Z3_set_param_value(Config, "timeout", "15000");
46 ~Z3Config() { Z3_del_config(Config); }
47 }; // end class Z3Config
49 // Function used to report errors
50 void Z3ErrorHandler(Z3_context Context, Z3_error_code Error) {
51 llvm::report_fatal_error("Z3 error: " +
52 llvm::Twine(Z3_get_error_msg_ex(Context, Error)));
55 /// Wrapper for Z3 context
56 class Z3Context : public SMTContext {
60 Z3Context() : SMTContext() {
61 Context = Z3_mk_context_rc(Z3Config().Config);
62 // The error function is set here because the context is the first object
63 // created by the backend
64 Z3_set_error_handler(Context, Z3ErrorHandler);
67 virtual ~Z3Context() {
68 Z3_del_context(Context);
71 }; // end class Z3Context
73 /// Wrapper for Z3 Sort
74 class Z3Sort : public SMTSort {
75 friend class Z3Solver;
82 /// Default constructor, mainly used by make_shared
83 Z3Sort(Z3Context &C, Z3_sort ZS) : SMTSort(), Context(C), Sort(ZS) {
84 Z3_inc_ref(Context.Context, reinterpret_cast<Z3_ast>(Sort));
87 /// Override implicit copy constructor for correct reference counting.
88 Z3Sort(const Z3Sort &Copy)
89 : SMTSort(), Context(Copy.Context), Sort(Copy.Sort) {
90 Z3_inc_ref(Context.Context, reinterpret_cast<Z3_ast>(Sort));
93 /// Provide move constructor
94 Z3Sort(Z3Sort &&Move) : SMTSort(), Context(Move.Context), Sort(nullptr) {
95 *this = std::move(Move);
98 /// Provide move assignment constructor
99 Z3Sort &operator=(Z3Sort &&Move) {
102 Z3_dec_ref(Context.Context, reinterpret_cast<Z3_ast>(Sort));
111 Z3_dec_ref(Context.Context, reinterpret_cast<Z3_ast>(Sort));
114 bool isBitvectorSortImpl() const override {
115 return (Z3_get_sort_kind(Context.Context, Sort) == Z3_BV_SORT);
118 bool isFloatSortImpl() const override {
119 return (Z3_get_sort_kind(Context.Context, Sort) == Z3_FLOATING_POINT_SORT);
122 bool isBooleanSortImpl() const override {
123 return (Z3_get_sort_kind(Context.Context, Sort) == Z3_BOOL_SORT);
126 unsigned getBitvectorSortSizeImpl() const override {
127 return Z3_get_bv_sort_size(Context.Context, Sort);
130 unsigned getFloatSortSizeImpl() const override {
131 return Z3_fpa_get_ebits(Context.Context, Sort) +
132 Z3_fpa_get_sbits(Context.Context, Sort);
135 bool equal_to(SMTSort const &Other) const override {
136 return Z3_is_eq_sort(Context.Context, Sort,
137 static_cast<const Z3Sort &>(Other).Sort);
140 Z3Sort &operator=(const Z3Sort &Move) {
141 Z3_inc_ref(Context.Context, reinterpret_cast<Z3_ast>(Move.Sort));
142 Z3_dec_ref(Context.Context, reinterpret_cast<Z3_ast>(Sort));
147 void print(raw_ostream &OS) const override {
148 OS << Z3_sort_to_string(Context.Context, Sort);
150 }; // end class Z3Sort
152 static const Z3Sort &toZ3Sort(const SMTSort &S) {
153 return static_cast<const Z3Sort &>(S);
156 class Z3Expr : public SMTExpr {
157 friend class Z3Solver;
164 Z3Expr(Z3Context &C, Z3_ast ZA) : SMTExpr(), Context(C), AST(ZA) {
165 Z3_inc_ref(Context.Context, AST);
168 /// Override implicit copy constructor for correct reference counting.
169 Z3Expr(const Z3Expr &Copy) : SMTExpr(), Context(Copy.Context), AST(Copy.AST) {
170 Z3_inc_ref(Context.Context, AST);
173 /// Provide move constructor
174 Z3Expr(Z3Expr &&Move) : SMTExpr(), Context(Move.Context), AST(nullptr) {
175 *this = std::move(Move);
178 /// Provide move assignment constructor
179 Z3Expr &operator=(Z3Expr &&Move) {
182 Z3_dec_ref(Context.Context, AST);
191 Z3_dec_ref(Context.Context, AST);
194 void Profile(llvm::FoldingSetNodeID &ID) const override {
195 ID.AddInteger(Z3_get_ast_hash(Context.Context, AST));
198 /// Comparison of AST equality, not model equivalence.
199 bool equal_to(SMTExpr const &Other) const override {
200 assert(Z3_is_eq_sort(Context.Context, Z3_get_sort(Context.Context, AST),
201 Z3_get_sort(Context.Context,
202 static_cast<const Z3Expr &>(Other).AST)) &&
203 "AST's must have the same sort");
204 return Z3_is_eq_ast(Context.Context, AST,
205 static_cast<const Z3Expr &>(Other).AST);
208 /// Override implicit move constructor for correct reference counting.
209 Z3Expr &operator=(const Z3Expr &Move) {
210 Z3_inc_ref(Context.Context, Move.AST);
211 Z3_dec_ref(Context.Context, AST);
216 void print(raw_ostream &OS) const override {
217 OS << Z3_ast_to_string(Context.Context, AST);
219 }; // end class Z3Expr
221 static const Z3Expr &toZ3Expr(const SMTExpr &E) {
222 return static_cast<const Z3Expr &>(E);
226 friend class Z3Solver;
233 Z3Model(Z3Context &C, Z3_model ZM) : Context(C), Model(ZM) {
234 assert(C.Context != nullptr);
235 Z3_model_inc_ref(Context.Context, Model);
238 /// Override implicit copy constructor for correct reference counting.
239 Z3Model(const Z3Model &Copy) : Context(Copy.Context), Model(Copy.Model) {
240 Z3_model_inc_ref(Context.Context, Model);
243 /// Provide move constructor
244 Z3Model(Z3Model &&Move) : Context(Move.Context), Model(nullptr) {
245 *this = std::move(Move);
248 /// Provide move assignment constructor
249 Z3Model &operator=(Z3Model &&Move) {
252 Z3_model_dec_ref(Context.Context, Model);
254 Move.Model = nullptr;
261 Z3_model_dec_ref(Context.Context, Model);
264 void print(raw_ostream &OS) const {
265 OS << Z3_model_to_string(Context.Context, Model);
268 LLVM_DUMP_METHOD void dump() const { print(llvm::errs()); }
269 }; // end class Z3Model
271 /// Get the corresponding IEEE floating-point type for a given bitwidth.
272 static const llvm::fltSemantics &getFloatSemantics(unsigned BitWidth) {
275 llvm_unreachable("Unsupported floating-point semantics!");
278 return llvm::APFloat::IEEEhalf();
280 return llvm::APFloat::IEEEsingle();
282 return llvm::APFloat::IEEEdouble();
284 return llvm::APFloat::IEEEquad();
288 // Determine whether two float semantics are equivalent
289 static bool areEquivalent(const llvm::fltSemantics &LHS,
290 const llvm::fltSemantics &RHS) {
291 return (llvm::APFloat::semanticsPrecision(LHS) ==
292 llvm::APFloat::semanticsPrecision(RHS)) &&
293 (llvm::APFloat::semanticsMinExponent(LHS) ==
294 llvm::APFloat::semanticsMinExponent(RHS)) &&
295 (llvm::APFloat::semanticsMaxExponent(LHS) ==
296 llvm::APFloat::semanticsMaxExponent(RHS)) &&
297 (llvm::APFloat::semanticsSizeInBits(LHS) ==
298 llvm::APFloat::semanticsSizeInBits(RHS));
301 } // end anonymous namespace
303 typedef llvm::ImmutableSet<std::pair<SymbolRef, Z3Expr>> ConstraintZ3Ty;
304 REGISTER_TRAIT_WITH_PROGRAMSTATE(ConstraintZ3, ConstraintZ3Ty)
308 class Z3Solver : public SMTSolver {
309 friend class Z3ConstraintManager;
316 Z3Solver() : SMTSolver(), Solver(Z3_mk_simple_solver(Context.Context)) {
317 Z3_solver_inc_ref(Context.Context, Solver);
320 /// Override implicit copy constructor for correct reference counting.
321 Z3Solver(const Z3Solver &Copy)
322 : SMTSolver(), Context(Copy.Context), Solver(Copy.Solver) {
323 Z3_solver_inc_ref(Context.Context, Solver);
326 /// Provide move constructor
327 Z3Solver(Z3Solver &&Move)
328 : SMTSolver(), Context(Move.Context), Solver(nullptr) {
329 *this = std::move(Move);
332 /// Provide move assignment constructor
333 Z3Solver &operator=(Z3Solver &&Move) {
336 Z3_solver_dec_ref(Context.Context, Solver);
337 Solver = Move.Solver;
338 Move.Solver = nullptr;
345 Z3_solver_dec_ref(Context.Context, Solver);
348 void addConstraint(const SMTExprRef &Exp) const override {
349 Z3_solver_assert(Context.Context, Solver, toZ3Expr(*Exp).AST);
352 SMTSortRef getBoolSort() override {
353 return std::make_shared<Z3Sort>(Context, Z3_mk_bool_sort(Context.Context));
356 SMTSortRef getBitvectorSort(unsigned BitWidth) override {
357 return std::make_shared<Z3Sort>(Context,
358 Z3_mk_bv_sort(Context.Context, BitWidth));
361 SMTSortRef getSort(const SMTExprRef &Exp) override {
362 return std::make_shared<Z3Sort>(
363 Context, Z3_get_sort(Context.Context, toZ3Expr(*Exp).AST));
366 SMTSortRef getFloat16Sort() override {
367 return std::make_shared<Z3Sort>(Context,
368 Z3_mk_fpa_sort_16(Context.Context));
371 SMTSortRef getFloat32Sort() override {
372 return std::make_shared<Z3Sort>(Context,
373 Z3_mk_fpa_sort_32(Context.Context));
376 SMTSortRef getFloat64Sort() override {
377 return std::make_shared<Z3Sort>(Context,
378 Z3_mk_fpa_sort_64(Context.Context));
381 SMTSortRef getFloat128Sort() override {
382 return std::make_shared<Z3Sort>(Context,
383 Z3_mk_fpa_sort_128(Context.Context));
386 SMTExprRef newExprRef(const SMTExpr &E) const override {
387 return std::make_shared<Z3Expr>(toZ3Expr(E));
390 SMTExprRef mkBVNeg(const SMTExprRef &Exp) override {
392 Z3Expr(Context, Z3_mk_bvneg(Context.Context, toZ3Expr(*Exp).AST)));
395 SMTExprRef mkBVNot(const SMTExprRef &Exp) override {
397 Z3Expr(Context, Z3_mk_bvnot(Context.Context, toZ3Expr(*Exp).AST)));
400 SMTExprRef mkNot(const SMTExprRef &Exp) override {
402 Z3Expr(Context, Z3_mk_not(Context.Context, toZ3Expr(*Exp).AST)));
405 SMTExprRef mkBVAdd(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
407 Z3Expr(Context, Z3_mk_bvadd(Context.Context, toZ3Expr(*LHS).AST,
408 toZ3Expr(*RHS).AST)));
411 SMTExprRef mkBVSub(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
413 Z3Expr(Context, Z3_mk_bvsub(Context.Context, toZ3Expr(*LHS).AST,
414 toZ3Expr(*RHS).AST)));
417 SMTExprRef mkBVMul(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
419 Z3Expr(Context, Z3_mk_bvmul(Context.Context, toZ3Expr(*LHS).AST,
420 toZ3Expr(*RHS).AST)));
423 SMTExprRef mkBVSRem(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
425 Z3Expr(Context, Z3_mk_bvsrem(Context.Context, toZ3Expr(*LHS).AST,
426 toZ3Expr(*RHS).AST)));
429 SMTExprRef mkBVURem(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
431 Z3Expr(Context, Z3_mk_bvurem(Context.Context, toZ3Expr(*LHS).AST,
432 toZ3Expr(*RHS).AST)));
435 SMTExprRef mkBVSDiv(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
437 Z3Expr(Context, Z3_mk_bvsdiv(Context.Context, toZ3Expr(*LHS).AST,
438 toZ3Expr(*RHS).AST)));
441 SMTExprRef mkBVUDiv(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
443 Z3Expr(Context, Z3_mk_bvudiv(Context.Context, toZ3Expr(*LHS).AST,
444 toZ3Expr(*RHS).AST)));
447 SMTExprRef mkBVShl(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
449 Z3Expr(Context, Z3_mk_bvshl(Context.Context, toZ3Expr(*LHS).AST,
450 toZ3Expr(*RHS).AST)));
453 SMTExprRef mkBVAshr(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
455 Z3Expr(Context, Z3_mk_bvashr(Context.Context, toZ3Expr(*LHS).AST,
456 toZ3Expr(*RHS).AST)));
459 SMTExprRef mkBVLshr(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
461 Z3Expr(Context, Z3_mk_bvlshr(Context.Context, toZ3Expr(*LHS).AST,
462 toZ3Expr(*RHS).AST)));
465 SMTExprRef mkBVXor(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
467 Z3Expr(Context, Z3_mk_bvxor(Context.Context, toZ3Expr(*LHS).AST,
468 toZ3Expr(*RHS).AST)));
471 SMTExprRef mkBVOr(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
473 Z3Expr(Context, Z3_mk_bvor(Context.Context, toZ3Expr(*LHS).AST,
474 toZ3Expr(*RHS).AST)));
477 SMTExprRef mkBVAnd(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
479 Z3Expr(Context, Z3_mk_bvand(Context.Context, toZ3Expr(*LHS).AST,
480 toZ3Expr(*RHS).AST)));
483 SMTExprRef mkBVUlt(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
485 Z3Expr(Context, Z3_mk_bvult(Context.Context, toZ3Expr(*LHS).AST,
486 toZ3Expr(*RHS).AST)));
489 SMTExprRef mkBVSlt(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
491 Z3Expr(Context, Z3_mk_bvslt(Context.Context, toZ3Expr(*LHS).AST,
492 toZ3Expr(*RHS).AST)));
495 SMTExprRef mkBVUgt(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
497 Z3Expr(Context, Z3_mk_bvugt(Context.Context, toZ3Expr(*LHS).AST,
498 toZ3Expr(*RHS).AST)));
501 SMTExprRef mkBVSgt(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
503 Z3Expr(Context, Z3_mk_bvsgt(Context.Context, toZ3Expr(*LHS).AST,
504 toZ3Expr(*RHS).AST)));
507 SMTExprRef mkBVUle(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
509 Z3Expr(Context, Z3_mk_bvule(Context.Context, toZ3Expr(*LHS).AST,
510 toZ3Expr(*RHS).AST)));
513 SMTExprRef mkBVSle(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
515 Z3Expr(Context, Z3_mk_bvsle(Context.Context, toZ3Expr(*LHS).AST,
516 toZ3Expr(*RHS).AST)));
519 SMTExprRef mkBVUge(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
521 Z3Expr(Context, Z3_mk_bvuge(Context.Context, toZ3Expr(*LHS).AST,
522 toZ3Expr(*RHS).AST)));
525 SMTExprRef mkBVSge(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
527 Z3Expr(Context, Z3_mk_bvsge(Context.Context, toZ3Expr(*LHS).AST,
528 toZ3Expr(*RHS).AST)));
531 SMTExprRef mkAnd(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
532 Z3_ast Args[2] = {toZ3Expr(*LHS).AST, toZ3Expr(*RHS).AST};
533 return newExprRef(Z3Expr(Context, Z3_mk_and(Context.Context, 2, Args)));
536 SMTExprRef mkOr(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
537 Z3_ast Args[2] = {toZ3Expr(*LHS).AST, toZ3Expr(*RHS).AST};
538 return newExprRef(Z3Expr(Context, Z3_mk_or(Context.Context, 2, Args)));
541 SMTExprRef mkEqual(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
543 Z3Expr(Context, Z3_mk_eq(Context.Context, toZ3Expr(*LHS).AST,
544 toZ3Expr(*RHS).AST)));
547 SMTExprRef mkFPNeg(const SMTExprRef &Exp) override {
549 Z3Expr(Context, Z3_mk_fpa_neg(Context.Context, toZ3Expr(*Exp).AST)));
552 SMTExprRef mkFPIsInfinite(const SMTExprRef &Exp) override {
553 return newExprRef(Z3Expr(
554 Context, Z3_mk_fpa_is_infinite(Context.Context, toZ3Expr(*Exp).AST)));
557 SMTExprRef mkFPIsNaN(const SMTExprRef &Exp) override {
559 Z3Expr(Context, Z3_mk_fpa_is_nan(Context.Context, toZ3Expr(*Exp).AST)));
562 SMTExprRef mkFPIsNormal(const SMTExprRef &Exp) override {
563 return newExprRef(Z3Expr(
564 Context, Z3_mk_fpa_is_normal(Context.Context, toZ3Expr(*Exp).AST)));
567 SMTExprRef mkFPIsZero(const SMTExprRef &Exp) override {
568 return newExprRef(Z3Expr(
569 Context, Z3_mk_fpa_is_zero(Context.Context, toZ3Expr(*Exp).AST)));
572 SMTExprRef mkFPMul(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
573 SMTExprRef RoundingMode = getFloatRoundingMode();
576 Z3_mk_fpa_mul(Context.Context, toZ3Expr(*LHS).AST,
577 toZ3Expr(*RHS).AST, toZ3Expr(*RoundingMode).AST)));
580 SMTExprRef mkFPDiv(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
581 SMTExprRef RoundingMode = getFloatRoundingMode();
584 Z3_mk_fpa_div(Context.Context, toZ3Expr(*LHS).AST,
585 toZ3Expr(*RHS).AST, toZ3Expr(*RoundingMode).AST)));
588 SMTExprRef mkFPRem(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
590 Z3Expr(Context, Z3_mk_fpa_rem(Context.Context, toZ3Expr(*LHS).AST,
591 toZ3Expr(*RHS).AST)));
594 SMTExprRef mkFPAdd(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
595 SMTExprRef RoundingMode = getFloatRoundingMode();
598 Z3_mk_fpa_add(Context.Context, toZ3Expr(*LHS).AST,
599 toZ3Expr(*RHS).AST, toZ3Expr(*RoundingMode).AST)));
602 SMTExprRef mkFPSub(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
603 SMTExprRef RoundingMode = getFloatRoundingMode();
606 Z3_mk_fpa_sub(Context.Context, toZ3Expr(*LHS).AST,
607 toZ3Expr(*RHS).AST, toZ3Expr(*RoundingMode).AST)));
610 SMTExprRef mkFPLt(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
612 Z3Expr(Context, Z3_mk_fpa_lt(Context.Context, toZ3Expr(*LHS).AST,
613 toZ3Expr(*RHS).AST)));
616 SMTExprRef mkFPGt(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
618 Z3Expr(Context, Z3_mk_fpa_gt(Context.Context, toZ3Expr(*LHS).AST,
619 toZ3Expr(*RHS).AST)));
622 SMTExprRef mkFPLe(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
624 Z3Expr(Context, Z3_mk_fpa_leq(Context.Context, toZ3Expr(*LHS).AST,
625 toZ3Expr(*RHS).AST)));
628 SMTExprRef mkFPGe(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
630 Z3Expr(Context, Z3_mk_fpa_geq(Context.Context, toZ3Expr(*LHS).AST,
631 toZ3Expr(*RHS).AST)));
634 SMTExprRef mkFPEqual(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
636 Z3Expr(Context, Z3_mk_fpa_eq(Context.Context, toZ3Expr(*LHS).AST,
637 toZ3Expr(*RHS).AST)));
640 SMTExprRef mkIte(const SMTExprRef &Cond, const SMTExprRef &T,
641 const SMTExprRef &F) override {
643 Z3Expr(Context, Z3_mk_ite(Context.Context, toZ3Expr(*Cond).AST,
644 toZ3Expr(*T).AST, toZ3Expr(*F).AST)));
647 SMTExprRef mkBVSignExt(unsigned i, const SMTExprRef &Exp) override {
648 return newExprRef(Z3Expr(
649 Context, Z3_mk_sign_ext(Context.Context, i, toZ3Expr(*Exp).AST)));
652 SMTExprRef mkBVZeroExt(unsigned i, const SMTExprRef &Exp) override {
653 return newExprRef(Z3Expr(
654 Context, Z3_mk_zero_ext(Context.Context, i, toZ3Expr(*Exp).AST)));
657 SMTExprRef mkBVExtract(unsigned High, unsigned Low,
658 const SMTExprRef &Exp) override {
659 return newExprRef(Z3Expr(Context, Z3_mk_extract(Context.Context, High, Low,
660 toZ3Expr(*Exp).AST)));
663 SMTExprRef mkBVConcat(const SMTExprRef &LHS, const SMTExprRef &RHS) override {
665 Z3Expr(Context, Z3_mk_concat(Context.Context, toZ3Expr(*LHS).AST,
666 toZ3Expr(*RHS).AST)));
669 SMTExprRef mkFPtoFP(const SMTExprRef &From, const SMTSortRef &To) override {
670 SMTExprRef RoundingMode = getFloatRoundingMode();
671 return newExprRef(Z3Expr(
673 Z3_mk_fpa_to_fp_float(Context.Context, toZ3Expr(*RoundingMode).AST,
674 toZ3Expr(*From).AST, toZ3Sort(*To).Sort)));
677 SMTExprRef mkFPtoSBV(const SMTExprRef &From, const SMTSortRef &To) override {
678 SMTExprRef RoundingMode = getFloatRoundingMode();
679 return newExprRef(Z3Expr(
681 Z3_mk_fpa_to_fp_signed(Context.Context, toZ3Expr(*RoundingMode).AST,
682 toZ3Expr(*From).AST, toZ3Sort(*To).Sort)));
685 SMTExprRef mkFPtoUBV(const SMTExprRef &From, const SMTSortRef &To) override {
686 SMTExprRef RoundingMode = getFloatRoundingMode();
687 return newExprRef(Z3Expr(
689 Z3_mk_fpa_to_fp_unsigned(Context.Context, toZ3Expr(*RoundingMode).AST,
690 toZ3Expr(*From).AST, toZ3Sort(*To).Sort)));
693 SMTExprRef mkSBVtoFP(const SMTExprRef &From, unsigned ToWidth) override {
694 SMTExprRef RoundingMode = getFloatRoundingMode();
695 return newExprRef(Z3Expr(
696 Context, Z3_mk_fpa_to_sbv(Context.Context, toZ3Expr(*RoundingMode).AST,
697 toZ3Expr(*From).AST, ToWidth)));
700 SMTExprRef mkUBVtoFP(const SMTExprRef &From, unsigned ToWidth) override {
701 SMTExprRef RoundingMode = getFloatRoundingMode();
702 return newExprRef(Z3Expr(
703 Context, Z3_mk_fpa_to_ubv(Context.Context, toZ3Expr(*RoundingMode).AST,
704 toZ3Expr(*From).AST, ToWidth)));
707 SMTExprRef mkBoolean(const bool b) override {
708 return newExprRef(Z3Expr(Context, b ? Z3_mk_true(Context.Context)
709 : Z3_mk_false(Context.Context)));
712 SMTExprRef mkBitvector(const llvm::APSInt Int, unsigned BitWidth) override {
713 const SMTSortRef Sort = getBitvectorSort(BitWidth);
715 Z3Expr(Context, Z3_mk_numeral(Context.Context, Int.toString(10).c_str(),
716 toZ3Sort(*Sort).Sort)));
719 SMTExprRef mkFloat(const llvm::APFloat Float) override {
721 getFloatSort(llvm::APFloat::semanticsSizeInBits(Float.getSemantics()));
723 llvm::APSInt Int = llvm::APSInt(Float.bitcastToAPInt(), false);
724 SMTExprRef Z3Int = mkBitvector(Int, Int.getBitWidth());
725 return newExprRef(Z3Expr(
726 Context, Z3_mk_fpa_to_fp_bv(Context.Context, toZ3Expr(*Z3Int).AST,
727 toZ3Sort(*Sort).Sort)));
730 SMTExprRef mkSymbol(const char *Name, SMTSortRef Sort) override {
732 Z3Expr(Context, Z3_mk_const(Context.Context,
733 Z3_mk_string_symbol(Context.Context, Name),
734 toZ3Sort(*Sort).Sort)));
737 llvm::APSInt getBitvector(const SMTExprRef &Exp, unsigned BitWidth,
738 bool isUnsigned) override {
739 return llvm::APSInt(llvm::APInt(
740 BitWidth, Z3_get_numeral_string(Context.Context, toZ3Expr(*Exp).AST),
744 bool getBoolean(const SMTExprRef &Exp) override {
745 return Z3_get_bool_value(Context.Context, toZ3Expr(*Exp).AST) == Z3_L_TRUE;
748 SMTExprRef getFloatRoundingMode() override {
749 // TODO: Don't assume nearest ties to even rounding mode
750 return newExprRef(Z3Expr(Context, Z3_mk_fpa_rne(Context.Context)));
753 SMTExprRef fromData(const SymbolID ID, const QualType &Ty,
754 uint64_t BitWidth) override {
755 llvm::Twine Name = "$" + llvm::Twine(ID);
756 return mkSymbol(Name.str().c_str(), mkSort(Ty, BitWidth));
759 SMTExprRef fromBoolean(const bool Bool) override {
761 Bool ? Z3_mk_true(Context.Context) : Z3_mk_false(Context.Context);
762 return newExprRef(Z3Expr(Context, AST));
765 SMTExprRef fromAPFloat(const llvm::APFloat &Float) override {
767 getFloatSort(llvm::APFloat::semanticsSizeInBits(Float.getSemantics()));
769 llvm::APSInt Int = llvm::APSInt(Float.bitcastToAPInt(), false);
770 SMTExprRef Z3Int = fromAPSInt(Int);
771 return newExprRef(Z3Expr(
772 Context, Z3_mk_fpa_to_fp_bv(Context.Context, toZ3Expr(*Z3Int).AST,
773 toZ3Sort(*Sort).Sort)));
776 SMTExprRef fromAPSInt(const llvm::APSInt &Int) override {
777 SMTSortRef Sort = getBitvectorSort(Int.getBitWidth());
778 Z3_ast AST = Z3_mk_numeral(Context.Context, Int.toString(10).c_str(),
779 toZ3Sort(*Sort).Sort);
780 return newExprRef(Z3Expr(Context, AST));
783 SMTExprRef fromInt(const char *Int, uint64_t BitWidth) override {
784 SMTSortRef Sort = getBitvectorSort(BitWidth);
785 Z3_ast AST = Z3_mk_numeral(Context.Context, Int, toZ3Sort(*Sort).Sort);
786 return newExprRef(Z3Expr(Context, AST));
789 bool toAPFloat(const SMTSortRef &Sort, const SMTExprRef &AST,
790 llvm::APFloat &Float, bool useSemantics) {
791 assert(Sort->isFloatSort() && "Unsupported sort to floating-point!");
793 llvm::APSInt Int(Sort->getFloatSortSize(), true);
794 const llvm::fltSemantics &Semantics =
795 getFloatSemantics(Sort->getFloatSortSize());
796 SMTSortRef BVSort = getBitvectorSort(Sort->getFloatSortSize());
797 if (!toAPSInt(BVSort, AST, Int, true)) {
801 if (useSemantics && !areEquivalent(Float.getSemantics(), Semantics)) {
802 assert(false && "Floating-point types don't match!");
806 Float = llvm::APFloat(Semantics, Int);
810 bool toAPSInt(const SMTSortRef &Sort, const SMTExprRef &AST,
811 llvm::APSInt &Int, bool useSemantics) {
812 if (Sort->isBitvectorSort()) {
813 if (useSemantics && Int.getBitWidth() != Sort->getBitvectorSortSize()) {
814 assert(false && "Bitvector types don't match!");
818 // FIXME: This function is also used to retrieve floating-point values,
819 // which can be 16, 32, 64 or 128 bits long. Bitvectors can be anything
820 // between 1 and 64 bits long, which is the reason we have this weird
821 // guard. In the future, we need proper calls in the backend to retrieve
822 // floating-points and its special values (NaN, +/-infinity, +/-zero),
823 // then we can drop this weird condition.
824 if (Sort->getBitvectorSortSize() <= 64 ||
825 Sort->getBitvectorSortSize() == 128) {
826 Int = getBitvector(AST, Int.getBitWidth(), Int.isUnsigned());
830 assert(false && "Bitwidth not supported!");
834 if (Sort->isBooleanSort()) {
835 if (useSemantics && Int.getBitWidth() < 1) {
836 assert(false && "Boolean type doesn't match!");
840 Int = llvm::APSInt(llvm::APInt(Int.getBitWidth(), getBoolean(AST)),
845 llvm_unreachable("Unsupported sort to integer!");
848 bool getInterpretation(const SMTExprRef &Exp, llvm::APSInt &Int) override {
849 Z3Model Model = getModel();
850 Z3_func_decl Func = Z3_get_app_decl(
851 Context.Context, Z3_to_app(Context.Context, toZ3Expr(*Exp).AST));
852 if (Z3_model_has_interp(Context.Context, Model.Model, Func) != Z3_L_TRUE)
855 SMTExprRef Assign = newExprRef(
857 Z3_model_get_const_interp(Context.Context, Model.Model, Func)));
858 SMTSortRef Sort = getSort(Assign);
859 return toAPSInt(Sort, Assign, Int, true);
862 bool getInterpretation(const SMTExprRef &Exp, llvm::APFloat &Float) override {
863 Z3Model Model = getModel();
864 Z3_func_decl Func = Z3_get_app_decl(
865 Context.Context, Z3_to_app(Context.Context, toZ3Expr(*Exp).AST));
866 if (Z3_model_has_interp(Context.Context, Model.Model, Func) != Z3_L_TRUE)
869 SMTExprRef Assign = newExprRef(
871 Z3_model_get_const_interp(Context.Context, Model.Model, Func)));
872 SMTSortRef Sort = getSort(Assign);
873 return toAPFloat(Sort, Assign, Float, true);
876 ConditionTruthVal check() const override {
877 Z3_lbool res = Z3_solver_check(Context.Context, Solver);
878 if (res == Z3_L_TRUE)
881 if (res == Z3_L_FALSE)
884 return ConditionTruthVal();
887 void push() override { return Z3_solver_push(Context.Context, Solver); }
889 void pop(unsigned NumStates = 1) override {
890 assert(Z3_solver_get_num_scopes(Context.Context, Solver) >= NumStates);
891 return Z3_solver_pop(Context.Context, Solver, NumStates);
894 /// Get a model from the solver. Caller should check the model is
897 return Z3Model(Context, Z3_solver_get_model(Context.Context, Solver));
900 /// Reset the solver and remove all constraints.
901 void reset() const override { Z3_solver_reset(Context.Context, Solver); }
903 void print(raw_ostream &OS) const override {
904 OS << Z3_solver_to_string(Context.Context, Solver);
906 }; // end class Z3Solver
908 class Z3ConstraintManager : public SMTConstraintManager {
909 SMTSolverRef Solver = CreateZ3Solver();
912 Z3ConstraintManager(SubEngine *SE, SValBuilder &SB)
913 : SMTConstraintManager(SE, SB, Solver) {}
915 void addStateConstraints(ProgramStateRef State) const override {
916 // TODO: Don't add all the constraints, only the relevant ones
917 ConstraintZ3Ty CZ = State->get<ConstraintZ3>();
918 ConstraintZ3Ty::iterator I = CZ.begin(), IE = CZ.end();
920 // Construct the logical AND of all the constraints
922 std::vector<SMTExprRef> ASTs;
924 SMTExprRef Constraint = Solver->newExprRef(I++->second);
926 Constraint = Solver->mkAnd(Constraint, Solver->newExprRef(I++->second));
929 Solver->addConstraint(Constraint);
933 bool canReasonAbout(SVal X) const override {
934 const TargetInfo &TI = getBasicVals().getContext().getTargetInfo();
936 Optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>();
940 const SymExpr *Sym = SymVal->getSymbol();
941 QualType Ty = Sym->getType();
943 // Complex types are not modeled
944 if (Ty->isComplexType() || Ty->isComplexIntegerType())
947 // Non-IEEE 754 floating-point types are not modeled
948 if ((Ty->isSpecificBuiltinType(BuiltinType::LongDouble) &&
949 (&TI.getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended() ||
950 &TI.getLongDoubleFormat() == &llvm::APFloat::PPCDoubleDouble())))
953 if (isa<SymbolData>(Sym))
956 SValBuilder &SVB = getSValBuilder();
958 if (const SymbolCast *SC = dyn_cast<SymbolCast>(Sym))
959 return canReasonAbout(SVB.makeSymbolVal(SC->getOperand()));
961 if (const BinarySymExpr *BSE = dyn_cast<BinarySymExpr>(Sym)) {
962 if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(BSE))
963 return canReasonAbout(SVB.makeSymbolVal(SIE->getLHS()));
965 if (const IntSymExpr *ISE = dyn_cast<IntSymExpr>(BSE))
966 return canReasonAbout(SVB.makeSymbolVal(ISE->getRHS()));
968 if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(BSE))
969 return canReasonAbout(SVB.makeSymbolVal(SSE->getLHS())) &&
970 canReasonAbout(SVB.makeSymbolVal(SSE->getRHS()));
973 llvm_unreachable("Unsupported expression to reason about!");
976 ProgramStateRef removeDeadBindings(ProgramStateRef State,
977 SymbolReaper &SymReaper) override {
978 ConstraintZ3Ty CZ = State->get<ConstraintZ3>();
979 ConstraintZ3Ty::Factory &CZFactory = State->get_context<ConstraintZ3>();
981 for (ConstraintZ3Ty::iterator I = CZ.begin(), E = CZ.end(); I != E; ++I) {
982 if (SymReaper.maybeDead(I->first))
983 CZ = CZFactory.remove(CZ, *I);
986 return State->set<ConstraintZ3>(CZ);
989 ProgramStateRef assumeExpr(ProgramStateRef State, SymbolRef Sym,
990 const SMTExprRef &Exp) override {
991 // Check the model, avoid simplifying AST to save time
992 if (checkModel(State, Exp).isConstrainedTrue())
993 return State->add<ConstraintZ3>(std::make_pair(Sym, toZ3Expr(*Exp)));
998 //==------------------------------------------------------------------------==/
1000 //==------------------------------------------------------------------------==/
1002 void print(ProgramStateRef St, raw_ostream &OS, const char *nl,
1003 const char *sep) override {
1005 ConstraintZ3Ty CZ = St->get<ConstraintZ3>();
1007 OS << nl << sep << "Constraints:";
1008 for (ConstraintZ3Ty::iterator I = CZ.begin(), E = CZ.end(); I != E; ++I) {
1009 OS << nl << ' ' << I->first << " : ";
1010 I->second.print(OS);
1014 }; // end class Z3ConstraintManager
1016 } // end anonymous namespace
1020 std::unique_ptr<SMTSolver> clang::ento::CreateZ3Solver() {
1021 #if CLANG_ANALYZER_WITH_Z3
1022 return llvm::make_unique<Z3Solver>();
1024 llvm::report_fatal_error("Clang was not compiled with Z3 support, rebuild "
1025 "with -DCLANG_ANALYZER_BUILD_Z3=ON",
1031 std::unique_ptr<ConstraintManager>
1032 ento::CreateZ3ConstraintManager(ProgramStateManager &StMgr, SubEngine *Eng) {
1033 #if CLANG_ANALYZER_WITH_Z3
1034 return llvm::make_unique<Z3ConstraintManager>(Eng, StMgr.getSValBuilder());
1036 llvm::report_fatal_error("Clang was not compiled with Z3 support, rebuild "
1037 "with -DCLANG_ANALYZER_BUILD_Z3=ON",