clang 23.0.0git
SMTConstraintManager.h
Go to the documentation of this file.
1//== SMTConstraintManager.h -------------------------------------*- C++ -*--==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines a SMT generic API, which will be the base class for
10// every SMT solver specific class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SMTCONSTRAINTMANAGER_H
15#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_SMTCONSTRAINTMANAGER_H
16
22#include <optional>
23
24typedef llvm::ImmutableSet<
25 std::pair<clang::ento::SymbolRef, const llvm::SMTExpr *>>
28
29namespace clang {
30namespace ento {
31
33 mutable llvm::SMTSolverRef Solver = llvm::CreateZ3Solver();
34
35public:
38 : SimpleConstraintManager(EE, SB) {
39 Solver->setBoolParam("model", true); // Enable model finding
40 Solver->setUnsignedParam("timeout", 15000 /*milliseconds*/);
41 }
42 virtual ~SMTConstraintManager() = default;
43
44 //===------------------------------------------------------------------===//
45 // Implementation for interface from SimpleConstraintManager.
46 //===------------------------------------------------------------------===//
47
49 bool Assumption) override {
51
52 QualType RetTy;
53 bool hasComparison;
54
55 std::optional<llvm::SMTExprRef> Exp =
56 SMTConv::getExpr(Solver, Ctx, Sym, RetTy, &hasComparison);
57 if (!Exp)
58 return assumeSymUnsupported(State, Sym, Assumption);
59 // Create zero comparison for implicit boolean cast, with reversed
60 // assumption
61 if (!hasComparison && !RetTy->isBooleanType())
62 return assumeExpr(
63 State, Sym,
64 SMTConv::getZeroExpr(Solver, Ctx, Exp.value(), RetTy, !Assumption));
65
66 return assumeExpr(State, Sym,
67 Assumption ? Exp.value() : Solver->mkNot(Exp.value()));
68 }
69
71 const llvm::APSInt &From,
72 const llvm::APSInt &To,
73 bool InRange) override {
75 std::optional<llvm::SMTExprRef> Expr =
76 SMTConv::getRangeExpr(Solver, Ctx, Sym, From, To, InRange);
77 if (!Expr)
78 return assumeSymUnsupported(State, Sym, false);
79 return assumeExpr(State, Sym, Expr.value());
80 }
81
83 bool Assumption) override {
84 // Skip anything that is unsupported
85 return State;
86 }
87
88 //===------------------------------------------------------------------===//
89 // Implementation for interface from ConstraintManager.
90 //===------------------------------------------------------------------===//
91
94
95 QualType RetTy;
96 // The expression may be casted, so we cannot call getZ3DataExpr() directly
97 std::optional<llvm::SMTExprRef> VarExp =
98 SMTConv::getExpr(Solver, Ctx, Sym, RetTy);
99 if (!VarExp)
100 return ConditionTruthVal();
101 llvm::SMTExprRef Exp = SMTConv::getZeroExpr(Solver, Ctx, VarExp.value(),
102 RetTy, /*Assumption=*/true);
103
104 // Negate the constraint
105 llvm::SMTExprRef NotExp = SMTConv::getZeroExpr(Solver, Ctx, VarExp.value(),
106 RetTy, /*Assumption=*/false);
107
108 ConditionTruthVal isSat = checkModel(State, Sym, Exp);
109 ConditionTruthVal isNotSat = checkModel(State, Sym, NotExp);
110
111 // Zero is the only possible solution
112 if (isSat.isConstrainedTrue() && isNotSat.isConstrainedFalse())
113 return true;
114
115 // Zero is not a solution
116 if (isSat.isConstrainedFalse() && isNotSat.isConstrainedTrue())
117 return false;
118
119 // Zero may be a solution
120 return ConditionTruthVal();
121 }
122
123 const llvm::APSInt *getSymVal(ProgramStateRef State,
124 SymbolRef Sym) const override {
126 ASTContext &Ctx = BVF.getContext();
127
128 if (const SymbolData *SD = dyn_cast<SymbolData>(Sym)) {
129 QualType Ty = Sym->getType();
130 assert(!Ty->isRealFloatingType());
131 llvm::APSInt Value(Ctx.getTypeSize(Ty),
133
134 // TODO: this should call checkModel so we can use the cache, however,
135 // this method tries to get the interpretation (the actual value) from
136 // the solver, which is currently not cached.
137
138 llvm::SMTExprRef Exp = SMTConv::fromData(Solver, Ctx, SD);
139
140 Solver->reset();
141 addStateConstraints(State);
142
143 // Constraints are unsatisfiable
144 std::optional<bool> isSat = Solver->check();
145 if (!isSat || !*isSat)
146 return nullptr;
147
148 // Model does not assign interpretation
149 if (!Solver->getInterpretation(Exp, Value))
150 return nullptr;
151
152 // A value has been obtained, check if it is the only value
153 llvm::SMTExprRef NotExp = SMTConv::fromBinOp(
154 Solver, Exp, BO_NE,
155 Ty->isBooleanType() ? Solver->mkBoolean(Value.getBoolValue())
156 : Solver->mkBitvector(Value, Value.getBitWidth()),
157 /*isSigned=*/false);
158
159 Solver->addConstraint(NotExp);
160
161 std::optional<bool> isNotSat = Solver->check();
162 if (!isNotSat || *isNotSat)
163 return nullptr;
164
165 // This is the only solution, store it
166 return BVF.getValue(Value).get();
167 }
168
169 if (const SymbolCast *SC = dyn_cast<SymbolCast>(Sym)) {
170 SymbolRef CastSym = SC->getOperand();
171 QualType CastTy = SC->getType();
172 // Skip the void type
173 if (CastTy->isVoidType())
174 return nullptr;
175
176 const llvm::APSInt *Value;
177 if (!(Value = getSymVal(State, CastSym)))
178 return nullptr;
179 return BVF.Convert(SC->getType(), *Value).get();
180 }
181
182 if (const auto *USE = dyn_cast<UnarySymExpr>(Sym)) {
183 const llvm::APSInt *Value;
184 if (!(Value = getSymVal(State, USE->getOperand())))
185 return nullptr;
186 std::optional<APSIntPtr> Res = BVF.evalAPSInt(USE->getOpcode(), *Value);
187 return Res ? Res.value().get() : nullptr;
188 }
189
190 if (const BinarySymExpr *BSE = dyn_cast<BinarySymExpr>(Sym)) {
191 const llvm::APSInt *LHS, *RHS;
192 if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(BSE)) {
193 LHS = getSymVal(State, SIE->getLHS());
194 RHS = SIE->getRHS().get();
195 } else if (const IntSymExpr *ISE = dyn_cast<IntSymExpr>(BSE)) {
196 LHS = ISE->getLHS().get();
197 RHS = getSymVal(State, ISE->getRHS());
198 } else if (const SymSymExpr *SSM = dyn_cast<SymSymExpr>(BSE)) {
199 // Early termination to avoid expensive call
200 LHS = getSymVal(State, SSM->getLHS());
201 RHS = LHS ? getSymVal(State, SSM->getRHS()) : nullptr;
202 } else {
203 llvm_unreachable("Unsupported binary expression to get symbol value!");
204 }
205
206 if (!LHS || !RHS)
207 return nullptr;
208
209 llvm::APSInt ConvertedLHS, ConvertedRHS;
210 QualType LTy, RTy;
211 std::tie(ConvertedLHS, LTy) = SMTConv::fixAPSInt(Ctx, *LHS);
212 std::tie(ConvertedRHS, RTy) = SMTConv::fixAPSInt(Ctx, *RHS);
214 Solver, Ctx, ConvertedLHS, LTy, ConvertedRHS, RTy);
215 std::optional<APSIntPtr> Res =
216 BVF.evalAPSInt(BSE->getOpcode(), ConvertedLHS, ConvertedRHS);
217 return Res ? Res.value().get() : nullptr;
218 }
219
220 llvm_unreachable("Unsupported expression to get symbol value!");
221 }
222
224 SymbolReaper &SymReaper) override {
225 auto CZ = State->get<ConstraintSMT>();
226 auto &CZFactory = State->get_context<ConstraintSMT>();
227
228 for (const auto &Entry : CZ) {
229 if (SymReaper.isDead(Entry.first))
230 CZ = CZFactory.remove(CZ, Entry);
231 }
232
233 return State->set<ConstraintSMT>(CZ);
234 }
235
236 void printJson(raw_ostream &Out, ProgramStateRef State, const char *NL = "\n",
237 unsigned int Space = 0, bool IsDot = false) const override {
238 ConstraintSMTType Constraints = State->get<ConstraintSMT>();
239
240 Indent(Out, Space, IsDot) << "\"constraints\": ";
241 if (Constraints.isEmpty()) {
242 Out << "null," << NL;
243 return;
244 }
245
246 ++Space;
247 Out << '[' << NL;
248 for (ConstraintSMTType::iterator I = Constraints.begin();
249 I != Constraints.end(); ++I) {
250 Indent(Out, Space, IsDot)
251 << "{ \"symbol\": \"" << I->first << "\", \"range\": \"";
252 I->second->print(Out);
253 Out << "\" }";
254
255 if (std::next(I) != Constraints.end())
256 Out << ',';
257 Out << NL;
258 }
259
260 --Space;
261 Indent(Out, Space, IsDot) << "],";
262 }
263
265 ProgramStateRef S2) const override {
266 return S1->get<ConstraintSMT>() == S2->get<ConstraintSMT>();
267 }
268
269 bool canReasonAbout(SVal X) const override {
271
272 std::optional<nonloc::SymbolVal> SymVal = X.getAs<nonloc::SymbolVal>();
273 if (!SymVal)
274 return true;
275
276 const SymExpr *Sym = SymVal->getSymbol();
277 QualType Ty = Sym->getType();
278
279 // Complex types are not modeled
280 if (Ty->isComplexType() || Ty->isComplexIntegerType())
281 return false;
282
283 // Non-IEEE 754 floating-point types are not modeled
284 if ((Ty->isSpecificBuiltinType(BuiltinType::LongDouble) &&
285 (&TI.getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended() ||
286 &TI.getLongDoubleFormat() == &llvm::APFloat::PPCDoubleDouble())))
287 return false;
288
289 if (Ty->isRealFloatingType())
290 return Solver->isFPSupported();
291
292 if (isa<SymbolData>(Sym))
293 return true;
294
296
297 if (const SymbolCast *SC = dyn_cast<SymbolCast>(Sym))
298 return canReasonAbout(SVB.makeSymbolVal(SC->getOperand()));
299
300 if (const auto *USE = dyn_cast<UnarySymExpr>(Sym))
301 return canReasonAbout(SVB.makeSymbolVal(USE->getOperand()));
302
303 if (const BinarySymExpr *BSE = dyn_cast<BinarySymExpr>(Sym)) {
304 if (const SymIntExpr *SIE = dyn_cast<SymIntExpr>(BSE))
305 return canReasonAbout(SVB.makeSymbolVal(SIE->getLHS()));
306
307 if (const IntSymExpr *ISE = dyn_cast<IntSymExpr>(BSE))
308 return canReasonAbout(SVB.makeSymbolVal(ISE->getRHS()));
309
310 if (const SymSymExpr *SSE = dyn_cast<SymSymExpr>(BSE))
311 return canReasonAbout(SVB.makeSymbolVal(SSE->getLHS())) &&
312 canReasonAbout(SVB.makeSymbolVal(SSE->getRHS()));
313 }
314
315 llvm_unreachable("Unsupported expression to reason about!");
316 }
317
318#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
319 /// Dumps SMT formula
320 LLVM_DUMP_METHOD void dump() const { Solver->dump(); }
321#endif
322
323protected:
324 // Check whether a new model is satisfiable, and update the program state.
326 const llvm::SMTExprRef &Exp) {
327 // Check the model, avoid simplifying AST to save time
328 if (checkModel(State, Sym, Exp).isConstrainedTrue())
329 return State->add<ConstraintSMT>(std::make_pair(Sym, Exp));
330
331 return nullptr;
332 }
333
334 /// Given a program state, construct the logical conjunction and add it to
335 /// the solver
336 virtual void addStateConstraints(ProgramStateRef State) const {
337 // TODO: Don't add all the constraints, only the relevant ones
338 auto CZ = State->get<ConstraintSMT>();
339 auto I = CZ.begin(), IE = CZ.end();
340
341 // Construct the logical AND of all the constraints
342 if (I != IE) {
343 llvm::SMTExprRef Constraint = I++->second;
344 while (I != IE) {
345 Constraint = Solver->mkAnd(Constraint, I++->second);
346 }
347
348 Solver->addConstraint(Constraint);
349 }
350 }
351
352 // Generate and check a Z3 model, using the given constraint.
354 const llvm::SMTExprRef &Exp) const {
355 ProgramStateRef NewState =
356 State->add<ConstraintSMT>(std::make_pair(Sym, Exp));
357
358 llvm::FoldingSetNodeID ID;
359 NewState->get<ConstraintSMT>().Profile(ID);
360
361 unsigned hash = ID.ComputeHash();
362 auto I = Cached.find(hash);
363 if (I != Cached.end())
364 return I->second;
365
366 Solver->reset();
367 addStateConstraints(NewState);
368
369 std::optional<bool> res = Solver->check();
370 return Cached[hash] = res ? ConditionTruthVal(*res) : ConditionTruthVal();
371 }
372
373 // Cache the result of an SMT query (true, false, unknown). The key is the
374 // hash of the constraints in a state
375 mutable llvm::DenseMap<unsigned, ConditionTruthVal> Cached;
376}; // end class SMTConstraintManager
377
378} // namespace ento
379} // namespace clang
380
381#endif
#define X(type, name)
Definition Value.h:97
#define REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, Type)
Declares a program state trait for type Type called Name, and introduce a type named NameTy.
llvm::ImmutableSet< std::pair< clang::ento::SymbolRef, const llvm::SMTExpr * > > ConstraintSMTType
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:927
This represents one expression.
Definition Expr.h:112
A (possibly-)qualified type.
Definition TypeBase.h:937
Exposes information about the current target.
Definition TargetInfo.h:227
const llvm::fltSemantics & getLongDoubleFormat() const
Definition TargetInfo.h:813
bool isVoidType() const
Definition TypeBase.h:9050
bool isBooleanType() const
Definition TypeBase.h:9187
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2293
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:761
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9019
bool isComplexIntegerType() const
Definition Type.cpp:767
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2409
LLVM_ATTRIBUTE_RETURNS_NONNULL const APSInt * get() const
Definition APSIntPtr.h:36
std::optional< APSIntPtr > evalAPSInt(UnaryOperator::Opcode Op, const llvm::APSInt &V1)
APSIntPtr Convert(const llvm::APSInt &To, const llvm::APSInt &From)
Convert - Create a new persistent APSInt with the same value as 'From' but with the bitwidth and sign...
Represents a symbolic expression involving a binary operator.
bool isConstrainedFalse() const
Return true if the constraint is perfectly constrained to 'false'.
bool isConstrainedTrue() const
Return true if the constraint is perfectly constrained to 'true'.
SMTConstraintManager(clang::ento::ExprEngine *EE, clang::ento::SValBuilder &SB)
virtual void addStateConstraints(ProgramStateRef State) const
Given a program state, construct the logical conjunction and add it to the solver.
bool canReasonAbout(SVal X) const override
canReasonAbout - Not all ConstraintManagers can accurately reason about all SVal values.
ProgramStateRef assumeSymInclusiveRange(ProgramStateRef State, SymbolRef Sym, const llvm::APSInt &From, const llvm::APSInt &To, bool InRange) override
Given a symbolic expression within the range [From, To], assume that it is true/false and generate th...
LLVM_DUMP_METHOD void dump() const
Dumps SMT formula.
ConditionTruthVal checkModel(ProgramStateRef State, SymbolRef Sym, const llvm::SMTExprRef &Exp) const
const llvm::APSInt * getSymVal(ProgramStateRef State, SymbolRef Sym) const override
If a symbol is perfectly constrained to a constant, attempt to return the concrete value.
ProgramStateRef removeDeadBindings(ProgramStateRef State, SymbolReaper &SymReaper) override
Scan all symbols referenced by the constraints.
ConditionTruthVal checkNull(ProgramStateRef State, SymbolRef Sym) override
Returns whether or not a symbol is known to be null ("true"), known to be non-null ("false"),...
ProgramStateRef assumeSym(ProgramStateRef State, SymbolRef Sym, bool Assumption) override
Given a symbolic expression that can be reasoned about, assume that it is true/false and generate the...
llvm::DenseMap< unsigned, ConditionTruthVal > Cached
virtual ~SMTConstraintManager()=default
virtual ProgramStateRef assumeExpr(ProgramStateRef State, SymbolRef Sym, const llvm::SMTExprRef &Exp)
void printJson(raw_ostream &Out, ProgramStateRef State, const char *NL="\n", unsigned int Space=0, bool IsDot=false) const override
ProgramStateRef assumeSymUnsupported(ProgramStateRef State, SymbolRef Sym, bool Assumption) override
Given a symbolic expression that cannot be reasoned about, assume that it is zero/nonzero and add it ...
bool haveEqualConstraints(ProgramStateRef S1, ProgramStateRef S2) const override
static std::optional< llvm::SMTExprRef > getRangeExpr(llvm::SMTSolverRef &Solver, ASTContext &Ctx, SymbolRef Sym, const llvm::APSInt &From, const llvm::APSInt &To, bool InRange)
Definition SMTConv.h:583
static llvm::SMTExprRef getZeroExpr(llvm::SMTSolverRef &Solver, ASTContext &Ctx, const llvm::SMTExprRef &Exp, QualType Ty, bool Assumption)
Definition SMTConv.h:552
static void doIntTypeConversion(llvm::SMTSolverRef &Solver, ASTContext &Ctx, T &LHS, QualType &LTy, T &RHS, QualType &RTy)
Definition SMTConv.h:744
static std::optional< llvm::SMTExprRef > getExpr(llvm::SMTSolverRef &Solver, ASTContext &Ctx, SymbolRef Sym, QualType &RetTy, bool *hasComparison=nullptr)
Definition SMTConv.h:542
static llvm::SMTExprRef fromData(llvm::SMTSolverRef &Solver, ASTContext &Ctx, const SymbolData *Sym)
Construct an SMTSolverRef from a SymbolData.
Definition SMTConv.h:325
static llvm::SMTExprRef fromBinOp(llvm::SMTSolverRef &Solver, const llvm::SMTExprRef &LHS, const BinaryOperator::Opcode Op, const llvm::SMTExprRef &RHS, bool isSigned)
Construct an SMTSolverRef from a binary operator.
Definition SMTConv.h:92
static std::pair< llvm::APSInt, QualType > fixAPSInt(ASTContext &Ctx, const llvm::APSInt &Int)
Definition SMTConv.h:645
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:57
SimpleConstraintManager(ExprEngine *exprengine, SValBuilder &SB)
Symbolic value.
Definition SymExpr.h:32
virtual QualType getType() const =0
Represents a cast expression.
A symbol representing data which can be stored in a memory location (region).
Definition SymExpr.h:138
A class responsible for cleaning up unused symbols.
bool isDead(SymbolRef sym)
Returns whether or not a symbol has been confirmed dead.
Represents symbolic expression that isn't a location.
Definition SVals.h:285
Defines the clang::TargetInfo interface.
BinarySymExprImpl< APSIntPtr, const SymExpr *, SymExpr::Kind::IntSymExprKind > IntSymExpr
Represents a symbolic expression like 3 - 'x'.
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
Definition SymExpr.h:133
BinarySymExprImpl< const SymExpr *, const SymExpr *, SymExpr::Kind::SymSymExprKind > SymSymExpr
Represents a symbolic expression like 'x' + 'y'.
BinarySymExprImpl< const SymExpr *, APSIntPtr, SymExpr::Kind::SymIntExprKind > SymIntExpr
Represents a symbolic expression like 'x' + 3.
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
Definition JsonSupport.h:21