1e5dd7070Spatrick // SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- C++ -*-
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // This file defines SimpleSValBuilder, a basic implementation of SValBuilder.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick
13e5dd7070Spatrick #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
14e5dd7070Spatrick #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
15ec727ea7Spatrick #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
16e5dd7070Spatrick #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
17e5dd7070Spatrick #include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h"
18*12c85518Srobert #include <optional>
19e5dd7070Spatrick
20e5dd7070Spatrick using namespace clang;
21e5dd7070Spatrick using namespace ento;
22e5dd7070Spatrick
23e5dd7070Spatrick namespace {
24e5dd7070Spatrick class SimpleSValBuilder : public SValBuilder {
25*12c85518Srobert
26*12c85518Srobert // Query the constraint manager whether the SVal has only one possible
27*12c85518Srobert // (integer) value. If that is the case, the value is returned. Otherwise,
28*12c85518Srobert // returns NULL.
29*12c85518Srobert // This is an implementation detail. Checkers should use `getKnownValue()`
30*12c85518Srobert // instead.
31*12c85518Srobert const llvm::APSInt *getConstValue(ProgramStateRef state, SVal V);
32*12c85518Srobert
33*12c85518Srobert // With one `simplifySValOnce` call, a compound symbols might collapse to
34*12c85518Srobert // simpler symbol tree that is still possible to further simplify. Thus, we
35*12c85518Srobert // do the simplification on a new symbol tree until we reach the simplest
36*12c85518Srobert // form, i.e. the fixpoint.
37*12c85518Srobert // Consider the following symbol `(b * b) * b * b` which has this tree:
38*12c85518Srobert // *
39*12c85518Srobert // / \
40*12c85518Srobert // * b
41*12c85518Srobert // / \
42*12c85518Srobert // / b
43*12c85518Srobert // (b * b)
44*12c85518Srobert // Now, if the `b * b == 1` new constraint is added then during the first
45*12c85518Srobert // iteration we have the following transformations:
46*12c85518Srobert // * *
47*12c85518Srobert // / \ / \
48*12c85518Srobert // * b --> b b
49*12c85518Srobert // / \
50*12c85518Srobert // / b
51*12c85518Srobert // 1
52*12c85518Srobert // We need another iteration to reach the final result `1`.
53*12c85518Srobert SVal simplifyUntilFixpoint(ProgramStateRef State, SVal Val);
54*12c85518Srobert
55*12c85518Srobert // Recursively descends into symbolic expressions and replaces symbols
56*12c85518Srobert // with their known values (in the sense of the getConstValue() method).
57*12c85518Srobert // We traverse the symbol tree and query the constraint values for the
58*12c85518Srobert // sub-trees and if a value is a constant we do the constant folding.
59*12c85518Srobert SVal simplifySValOnce(ProgramStateRef State, SVal V);
60*12c85518Srobert
61e5dd7070Spatrick public:
SimpleSValBuilder(llvm::BumpPtrAllocator & alloc,ASTContext & context,ProgramStateManager & stateMgr)62e5dd7070Spatrick SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
63e5dd7070Spatrick ProgramStateManager &stateMgr)
64e5dd7070Spatrick : SValBuilder(alloc, context, stateMgr) {}
~SimpleSValBuilder()65e5dd7070Spatrick ~SimpleSValBuilder() override {}
66e5dd7070Spatrick
67e5dd7070Spatrick SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
68e5dd7070Spatrick NonLoc lhs, NonLoc rhs, QualType resultTy) override;
69e5dd7070Spatrick SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
70e5dd7070Spatrick Loc lhs, Loc rhs, QualType resultTy) override;
71e5dd7070Spatrick SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
72e5dd7070Spatrick Loc lhs, NonLoc rhs, QualType resultTy) override;
73e5dd7070Spatrick
74*12c85518Srobert /// Evaluates a given SVal by recursively evaluating and
75*12c85518Srobert /// simplifying the children SVals. If the SVal has only one possible
76e5dd7070Spatrick /// (integer) value, that value is returned. Otherwise, returns NULL.
77e5dd7070Spatrick const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override;
78e5dd7070Spatrick
79e5dd7070Spatrick SVal simplifySVal(ProgramStateRef State, SVal V) override;
80e5dd7070Spatrick
81e5dd7070Spatrick SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
82e5dd7070Spatrick const llvm::APSInt &RHS, QualType resultTy);
83e5dd7070Spatrick };
84e5dd7070Spatrick } // end anonymous namespace
85e5dd7070Spatrick
createSimpleSValBuilder(llvm::BumpPtrAllocator & alloc,ASTContext & context,ProgramStateManager & stateMgr)86e5dd7070Spatrick SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
87e5dd7070Spatrick ASTContext &context,
88e5dd7070Spatrick ProgramStateManager &stateMgr) {
89e5dd7070Spatrick return new SimpleSValBuilder(alloc, context, stateMgr);
90e5dd7070Spatrick }
91e5dd7070Spatrick
92*12c85518Srobert // Checks if the negation the value and flipping sign preserve
93*12c85518Srobert // the semantics on the operation in the resultType
isNegationValuePreserving(const llvm::APSInt & Value,APSIntType ResultType)94*12c85518Srobert static bool isNegationValuePreserving(const llvm::APSInt &Value,
95*12c85518Srobert APSIntType ResultType) {
96*12c85518Srobert const unsigned ValueBits = Value.getSignificantBits();
97*12c85518Srobert if (ValueBits == ResultType.getBitWidth()) {
98*12c85518Srobert // The value is the lowest negative value that is representable
99*12c85518Srobert // in signed integer with bitWith of result type. The
100*12c85518Srobert // negation is representable if resultType is unsigned.
101*12c85518Srobert return ResultType.isUnsigned();
102e5dd7070Spatrick }
103e5dd7070Spatrick
104*12c85518Srobert // If resultType bitWith is higher that number of bits required
105*12c85518Srobert // to represent RHS, the sign flip produce same value.
106*12c85518Srobert return ValueBits < ResultType.getBitWidth();
107e5dd7070Spatrick }
108e5dd7070Spatrick
109e5dd7070Spatrick //===----------------------------------------------------------------------===//
110e5dd7070Spatrick // Transfer function for binary operators.
111e5dd7070Spatrick //===----------------------------------------------------------------------===//
112e5dd7070Spatrick
MakeSymIntVal(const SymExpr * LHS,BinaryOperator::Opcode op,const llvm::APSInt & RHS,QualType resultTy)113e5dd7070Spatrick SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
114e5dd7070Spatrick BinaryOperator::Opcode op,
115e5dd7070Spatrick const llvm::APSInt &RHS,
116e5dd7070Spatrick QualType resultTy) {
117e5dd7070Spatrick bool isIdempotent = false;
118e5dd7070Spatrick
119e5dd7070Spatrick // Check for a few special cases with known reductions first.
120e5dd7070Spatrick switch (op) {
121e5dd7070Spatrick default:
122e5dd7070Spatrick // We can't reduce this case; just treat it normally.
123e5dd7070Spatrick break;
124e5dd7070Spatrick case BO_Mul:
125e5dd7070Spatrick // a*0 and a*1
126e5dd7070Spatrick if (RHS == 0)
127e5dd7070Spatrick return makeIntVal(0, resultTy);
128e5dd7070Spatrick else if (RHS == 1)
129e5dd7070Spatrick isIdempotent = true;
130e5dd7070Spatrick break;
131e5dd7070Spatrick case BO_Div:
132e5dd7070Spatrick // a/0 and a/1
133e5dd7070Spatrick if (RHS == 0)
134e5dd7070Spatrick // This is also handled elsewhere.
135e5dd7070Spatrick return UndefinedVal();
136e5dd7070Spatrick else if (RHS == 1)
137e5dd7070Spatrick isIdempotent = true;
138e5dd7070Spatrick break;
139e5dd7070Spatrick case BO_Rem:
140e5dd7070Spatrick // a%0 and a%1
141e5dd7070Spatrick if (RHS == 0)
142e5dd7070Spatrick // This is also handled elsewhere.
143e5dd7070Spatrick return UndefinedVal();
144e5dd7070Spatrick else if (RHS == 1)
145e5dd7070Spatrick return makeIntVal(0, resultTy);
146e5dd7070Spatrick break;
147e5dd7070Spatrick case BO_Add:
148e5dd7070Spatrick case BO_Sub:
149e5dd7070Spatrick case BO_Shl:
150e5dd7070Spatrick case BO_Shr:
151e5dd7070Spatrick case BO_Xor:
152e5dd7070Spatrick // a+0, a-0, a<<0, a>>0, a^0
153e5dd7070Spatrick if (RHS == 0)
154e5dd7070Spatrick isIdempotent = true;
155e5dd7070Spatrick break;
156e5dd7070Spatrick case BO_And:
157e5dd7070Spatrick // a&0 and a&(~0)
158e5dd7070Spatrick if (RHS == 0)
159e5dd7070Spatrick return makeIntVal(0, resultTy);
160*12c85518Srobert else if (RHS.isAllOnes())
161e5dd7070Spatrick isIdempotent = true;
162e5dd7070Spatrick break;
163e5dd7070Spatrick case BO_Or:
164e5dd7070Spatrick // a|0 and a|(~0)
165e5dd7070Spatrick if (RHS == 0)
166e5dd7070Spatrick isIdempotent = true;
167*12c85518Srobert else if (RHS.isAllOnes()) {
168e5dd7070Spatrick const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
169e5dd7070Spatrick return nonloc::ConcreteInt(Result);
170e5dd7070Spatrick }
171e5dd7070Spatrick break;
172e5dd7070Spatrick }
173e5dd7070Spatrick
174e5dd7070Spatrick // Idempotent ops (like a*1) can still change the type of an expression.
175a9ac8606Spatrick // Wrap the LHS up in a NonLoc again and let evalCast do the
176e5dd7070Spatrick // dirty work.
177e5dd7070Spatrick if (isIdempotent)
178a9ac8606Spatrick return evalCast(nonloc::SymbolVal(LHS), resultTy, QualType{});
179e5dd7070Spatrick
180e5dd7070Spatrick // If we reach this point, the expression cannot be simplified.
181e5dd7070Spatrick // Make a SymbolVal for the entire expression, after converting the RHS.
182e5dd7070Spatrick const llvm::APSInt *ConvertedRHS = &RHS;
183e5dd7070Spatrick if (BinaryOperator::isComparisonOp(op)) {
184e5dd7070Spatrick // We're looking for a type big enough to compare the symbolic value
185e5dd7070Spatrick // with the given constant.
186e5dd7070Spatrick // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
187e5dd7070Spatrick ASTContext &Ctx = getContext();
188e5dd7070Spatrick QualType SymbolType = LHS->getType();
189e5dd7070Spatrick uint64_t ValWidth = RHS.getBitWidth();
190e5dd7070Spatrick uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
191e5dd7070Spatrick
192e5dd7070Spatrick if (ValWidth < TypeWidth) {
193e5dd7070Spatrick // If the value is too small, extend it.
194e5dd7070Spatrick ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
195e5dd7070Spatrick } else if (ValWidth == TypeWidth) {
196e5dd7070Spatrick // If the value is signed but the symbol is unsigned, do the comparison
197e5dd7070Spatrick // in unsigned space. [C99 6.3.1.8]
198e5dd7070Spatrick // (For the opposite case, the value is already unsigned.)
199e5dd7070Spatrick if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
200e5dd7070Spatrick ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
201e5dd7070Spatrick }
202*12c85518Srobert } else if (BinaryOperator::isAdditiveOp(op) && RHS.isNegative()) {
203*12c85518Srobert // Change a+(-N) into a-N, and a-(-N) into a+N
204*12c85518Srobert // Adjust addition/subtraction of negative value, to
205*12c85518Srobert // subtraction/addition of the negated value.
206*12c85518Srobert APSIntType resultIntTy = BasicVals.getAPSIntType(resultTy);
207*12c85518Srobert if (isNegationValuePreserving(RHS, resultIntTy)) {
208*12c85518Srobert ConvertedRHS = &BasicVals.getValue(-resultIntTy.convert(RHS));
209*12c85518Srobert op = (op == BO_Add) ? BO_Sub : BO_Add;
210*12c85518Srobert } else {
211*12c85518Srobert ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
212*12c85518Srobert }
213e5dd7070Spatrick } else
214e5dd7070Spatrick ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
215e5dd7070Spatrick
216e5dd7070Spatrick return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
217e5dd7070Spatrick }
218e5dd7070Spatrick
219e5dd7070Spatrick // See if Sym is known to be a relation Rel with Bound.
isInRelation(BinaryOperator::Opcode Rel,SymbolRef Sym,llvm::APSInt Bound,ProgramStateRef State)220e5dd7070Spatrick static bool isInRelation(BinaryOperator::Opcode Rel, SymbolRef Sym,
221e5dd7070Spatrick llvm::APSInt Bound, ProgramStateRef State) {
222e5dd7070Spatrick SValBuilder &SVB = State->getStateManager().getSValBuilder();
223e5dd7070Spatrick SVal Result =
224e5dd7070Spatrick SVB.evalBinOpNN(State, Rel, nonloc::SymbolVal(Sym),
225e5dd7070Spatrick nonloc::ConcreteInt(Bound), SVB.getConditionType());
226e5dd7070Spatrick if (auto DV = Result.getAs<DefinedSVal>()) {
227e5dd7070Spatrick return !State->assume(*DV, false);
228e5dd7070Spatrick }
229e5dd7070Spatrick return false;
230e5dd7070Spatrick }
231e5dd7070Spatrick
232e5dd7070Spatrick // See if Sym is known to be within [min/4, max/4], where min and max
233e5dd7070Spatrick // are the bounds of the symbol's integral type. With such symbols,
234e5dd7070Spatrick // some manipulations can be performed without the risk of overflow.
235e5dd7070Spatrick // assume() doesn't cause infinite recursion because we should be dealing
236e5dd7070Spatrick // with simpler symbols on every recursive call.
isWithinConstantOverflowBounds(SymbolRef Sym,ProgramStateRef State)237e5dd7070Spatrick static bool isWithinConstantOverflowBounds(SymbolRef Sym,
238e5dd7070Spatrick ProgramStateRef State) {
239e5dd7070Spatrick SValBuilder &SVB = State->getStateManager().getSValBuilder();
240e5dd7070Spatrick BasicValueFactory &BV = SVB.getBasicValueFactory();
241e5dd7070Spatrick
242e5dd7070Spatrick QualType T = Sym->getType();
243e5dd7070Spatrick assert(T->isSignedIntegerOrEnumerationType() &&
244e5dd7070Spatrick "This only works with signed integers!");
245e5dd7070Spatrick APSIntType AT = BV.getAPSIntType(T);
246e5dd7070Spatrick
247e5dd7070Spatrick llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
248e5dd7070Spatrick return isInRelation(BO_LE, Sym, Max, State) &&
249e5dd7070Spatrick isInRelation(BO_GE, Sym, Min, State);
250e5dd7070Spatrick }
251e5dd7070Spatrick
252e5dd7070Spatrick // Same for the concrete integers: see if I is within [min/4, max/4].
isWithinConstantOverflowBounds(llvm::APSInt I)253e5dd7070Spatrick static bool isWithinConstantOverflowBounds(llvm::APSInt I) {
254e5dd7070Spatrick APSIntType AT(I);
255e5dd7070Spatrick assert(!AT.isUnsigned() &&
256e5dd7070Spatrick "This only works with signed integers!");
257e5dd7070Spatrick
258e5dd7070Spatrick llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
259e5dd7070Spatrick return (I <= Max) && (I >= -Max);
260e5dd7070Spatrick }
261e5dd7070Spatrick
262e5dd7070Spatrick static std::pair<SymbolRef, llvm::APSInt>
decomposeSymbol(SymbolRef Sym,BasicValueFactory & BV)263e5dd7070Spatrick decomposeSymbol(SymbolRef Sym, BasicValueFactory &BV) {
264e5dd7070Spatrick if (const auto *SymInt = dyn_cast<SymIntExpr>(Sym))
265e5dd7070Spatrick if (BinaryOperator::isAdditiveOp(SymInt->getOpcode()))
266e5dd7070Spatrick return std::make_pair(SymInt->getLHS(),
267e5dd7070Spatrick (SymInt->getOpcode() == BO_Add) ?
268e5dd7070Spatrick (SymInt->getRHS()) :
269e5dd7070Spatrick (-SymInt->getRHS()));
270e5dd7070Spatrick
271e5dd7070Spatrick // Fail to decompose: "reduce" the problem to the "$x + 0" case.
272e5dd7070Spatrick return std::make_pair(Sym, BV.getValue(0, Sym->getType()));
273e5dd7070Spatrick }
274e5dd7070Spatrick
275e5dd7070Spatrick // Simplify "(LSym + LInt) Op (RSym + RInt)" assuming all values are of the
276e5dd7070Spatrick // same signed integral type and no overflows occur (which should be checked
277e5dd7070Spatrick // by the caller).
doRearrangeUnchecked(ProgramStateRef State,BinaryOperator::Opcode Op,SymbolRef LSym,llvm::APSInt LInt,SymbolRef RSym,llvm::APSInt RInt)278e5dd7070Spatrick static NonLoc doRearrangeUnchecked(ProgramStateRef State,
279e5dd7070Spatrick BinaryOperator::Opcode Op,
280e5dd7070Spatrick SymbolRef LSym, llvm::APSInt LInt,
281e5dd7070Spatrick SymbolRef RSym, llvm::APSInt RInt) {
282e5dd7070Spatrick SValBuilder &SVB = State->getStateManager().getSValBuilder();
283e5dd7070Spatrick BasicValueFactory &BV = SVB.getBasicValueFactory();
284e5dd7070Spatrick SymbolManager &SymMgr = SVB.getSymbolManager();
285e5dd7070Spatrick
286e5dd7070Spatrick QualType SymTy = LSym->getType();
287e5dd7070Spatrick assert(SymTy == RSym->getType() &&
288e5dd7070Spatrick "Symbols are not of the same type!");
289e5dd7070Spatrick assert(APSIntType(LInt) == BV.getAPSIntType(SymTy) &&
290e5dd7070Spatrick "Integers are not of the same type as symbols!");
291e5dd7070Spatrick assert(APSIntType(RInt) == BV.getAPSIntType(SymTy) &&
292e5dd7070Spatrick "Integers are not of the same type as symbols!");
293e5dd7070Spatrick
294e5dd7070Spatrick QualType ResultTy;
295e5dd7070Spatrick if (BinaryOperator::isComparisonOp(Op))
296e5dd7070Spatrick ResultTy = SVB.getConditionType();
297e5dd7070Spatrick else if (BinaryOperator::isAdditiveOp(Op))
298e5dd7070Spatrick ResultTy = SymTy;
299e5dd7070Spatrick else
300e5dd7070Spatrick llvm_unreachable("Operation not suitable for unchecked rearrangement!");
301e5dd7070Spatrick
302e5dd7070Spatrick if (LSym == RSym)
303e5dd7070Spatrick return SVB.evalBinOpNN(State, Op, nonloc::ConcreteInt(LInt),
304e5dd7070Spatrick nonloc::ConcreteInt(RInt), ResultTy)
305e5dd7070Spatrick .castAs<NonLoc>();
306e5dd7070Spatrick
307e5dd7070Spatrick SymbolRef ResultSym = nullptr;
308e5dd7070Spatrick BinaryOperator::Opcode ResultOp;
309e5dd7070Spatrick llvm::APSInt ResultInt;
310e5dd7070Spatrick if (BinaryOperator::isComparisonOp(Op)) {
311e5dd7070Spatrick // Prefer comparing to a non-negative number.
312e5dd7070Spatrick // FIXME: Maybe it'd be better to have consistency in
313e5dd7070Spatrick // "$x - $y" vs. "$y - $x" because those are solver's keys.
314e5dd7070Spatrick if (LInt > RInt) {
315e5dd7070Spatrick ResultSym = SymMgr.getSymSymExpr(RSym, BO_Sub, LSym, SymTy);
316e5dd7070Spatrick ResultOp = BinaryOperator::reverseComparisonOp(Op);
317e5dd7070Spatrick ResultInt = LInt - RInt; // Opposite order!
318e5dd7070Spatrick } else {
319e5dd7070Spatrick ResultSym = SymMgr.getSymSymExpr(LSym, BO_Sub, RSym, SymTy);
320e5dd7070Spatrick ResultOp = Op;
321e5dd7070Spatrick ResultInt = RInt - LInt; // Opposite order!
322e5dd7070Spatrick }
323e5dd7070Spatrick } else {
324e5dd7070Spatrick ResultSym = SymMgr.getSymSymExpr(LSym, Op, RSym, SymTy);
325e5dd7070Spatrick ResultInt = (Op == BO_Add) ? (LInt + RInt) : (LInt - RInt);
326e5dd7070Spatrick ResultOp = BO_Add;
327e5dd7070Spatrick // Bring back the cosmetic difference.
328e5dd7070Spatrick if (ResultInt < 0) {
329e5dd7070Spatrick ResultInt = -ResultInt;
330e5dd7070Spatrick ResultOp = BO_Sub;
331e5dd7070Spatrick } else if (ResultInt == 0) {
332e5dd7070Spatrick // Shortcut: Simplify "$x + 0" to "$x".
333e5dd7070Spatrick return nonloc::SymbolVal(ResultSym);
334e5dd7070Spatrick }
335e5dd7070Spatrick }
336e5dd7070Spatrick const llvm::APSInt &PersistentResultInt = BV.getValue(ResultInt);
337e5dd7070Spatrick return nonloc::SymbolVal(
338e5dd7070Spatrick SymMgr.getSymIntExpr(ResultSym, ResultOp, PersistentResultInt, ResultTy));
339e5dd7070Spatrick }
340e5dd7070Spatrick
341e5dd7070Spatrick // Rearrange if symbol type matches the result type and if the operator is a
342e5dd7070Spatrick // comparison operator, both symbol and constant must be within constant
343e5dd7070Spatrick // overflow bounds.
shouldRearrange(ProgramStateRef State,BinaryOperator::Opcode Op,SymbolRef Sym,llvm::APSInt Int,QualType Ty)344e5dd7070Spatrick static bool shouldRearrange(ProgramStateRef State, BinaryOperator::Opcode Op,
345e5dd7070Spatrick SymbolRef Sym, llvm::APSInt Int, QualType Ty) {
346e5dd7070Spatrick return Sym->getType() == Ty &&
347e5dd7070Spatrick (!BinaryOperator::isComparisonOp(Op) ||
348e5dd7070Spatrick (isWithinConstantOverflowBounds(Sym, State) &&
349e5dd7070Spatrick isWithinConstantOverflowBounds(Int)));
350e5dd7070Spatrick }
351e5dd7070Spatrick
tryRearrange(ProgramStateRef State,BinaryOperator::Opcode Op,NonLoc Lhs,NonLoc Rhs,QualType ResultTy)352*12c85518Srobert static std::optional<NonLoc> tryRearrange(ProgramStateRef State,
353e5dd7070Spatrick BinaryOperator::Opcode Op, NonLoc Lhs,
354e5dd7070Spatrick NonLoc Rhs, QualType ResultTy) {
355e5dd7070Spatrick ProgramStateManager &StateMgr = State->getStateManager();
356e5dd7070Spatrick SValBuilder &SVB = StateMgr.getSValBuilder();
357e5dd7070Spatrick
358e5dd7070Spatrick // We expect everything to be of the same type - this type.
359e5dd7070Spatrick QualType SingleTy;
360e5dd7070Spatrick
361e5dd7070Spatrick // FIXME: After putting complexity threshold to the symbols we can always
362e5dd7070Spatrick // rearrange additive operations but rearrange comparisons only if
363e5dd7070Spatrick // option is set.
364*12c85518Srobert if (!SVB.getAnalyzerOptions().ShouldAggressivelySimplifyBinaryOperation)
365*12c85518Srobert return std::nullopt;
366e5dd7070Spatrick
367e5dd7070Spatrick SymbolRef LSym = Lhs.getAsSymbol();
368e5dd7070Spatrick if (!LSym)
369*12c85518Srobert return std::nullopt;
370e5dd7070Spatrick
371e5dd7070Spatrick if (BinaryOperator::isComparisonOp(Op)) {
372e5dd7070Spatrick SingleTy = LSym->getType();
373e5dd7070Spatrick if (ResultTy != SVB.getConditionType())
374*12c85518Srobert return std::nullopt;
375e5dd7070Spatrick // Initialize SingleTy later with a symbol's type.
376e5dd7070Spatrick } else if (BinaryOperator::isAdditiveOp(Op)) {
377e5dd7070Spatrick SingleTy = ResultTy;
378e5dd7070Spatrick if (LSym->getType() != SingleTy)
379*12c85518Srobert return std::nullopt;
380e5dd7070Spatrick } else {
381e5dd7070Spatrick // Don't rearrange other operations.
382*12c85518Srobert return std::nullopt;
383e5dd7070Spatrick }
384e5dd7070Spatrick
385e5dd7070Spatrick assert(!SingleTy.isNull() && "We should have figured out the type by now!");
386e5dd7070Spatrick
387e5dd7070Spatrick // Rearrange signed symbolic expressions only
388e5dd7070Spatrick if (!SingleTy->isSignedIntegerOrEnumerationType())
389*12c85518Srobert return std::nullopt;
390e5dd7070Spatrick
391e5dd7070Spatrick SymbolRef RSym = Rhs.getAsSymbol();
392e5dd7070Spatrick if (!RSym || RSym->getType() != SingleTy)
393*12c85518Srobert return std::nullopt;
394e5dd7070Spatrick
395e5dd7070Spatrick BasicValueFactory &BV = State->getBasicVals();
396e5dd7070Spatrick llvm::APSInt LInt, RInt;
397e5dd7070Spatrick std::tie(LSym, LInt) = decomposeSymbol(LSym, BV);
398e5dd7070Spatrick std::tie(RSym, RInt) = decomposeSymbol(RSym, BV);
399e5dd7070Spatrick if (!shouldRearrange(State, Op, LSym, LInt, SingleTy) ||
400e5dd7070Spatrick !shouldRearrange(State, Op, RSym, RInt, SingleTy))
401*12c85518Srobert return std::nullopt;
402e5dd7070Spatrick
403e5dd7070Spatrick // We know that no overflows can occur anymore.
404e5dd7070Spatrick return doRearrangeUnchecked(State, Op, LSym, LInt, RSym, RInt);
405e5dd7070Spatrick }
406e5dd7070Spatrick
evalBinOpNN(ProgramStateRef state,BinaryOperator::Opcode op,NonLoc lhs,NonLoc rhs,QualType resultTy)407e5dd7070Spatrick SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
408e5dd7070Spatrick BinaryOperator::Opcode op,
409e5dd7070Spatrick NonLoc lhs, NonLoc rhs,
410e5dd7070Spatrick QualType resultTy) {
411e5dd7070Spatrick NonLoc InputLHS = lhs;
412e5dd7070Spatrick NonLoc InputRHS = rhs;
413e5dd7070Spatrick
414*12c85518Srobert // Constraints may have changed since the creation of a bound SVal. Check if
415*12c85518Srobert // the values can be simplified based on those new constraints.
416*12c85518Srobert SVal simplifiedLhs = simplifySVal(state, lhs);
417*12c85518Srobert SVal simplifiedRhs = simplifySVal(state, rhs);
418*12c85518Srobert if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>())
419*12c85518Srobert lhs = *simplifiedLhsAsNonLoc;
420*12c85518Srobert if (auto simplifiedRhsAsNonLoc = simplifiedRhs.getAs<NonLoc>())
421*12c85518Srobert rhs = *simplifiedRhsAsNonLoc;
422*12c85518Srobert
423e5dd7070Spatrick // Handle trivial case where left-side and right-side are the same.
424e5dd7070Spatrick if (lhs == rhs)
425e5dd7070Spatrick switch (op) {
426e5dd7070Spatrick default:
427e5dd7070Spatrick break;
428e5dd7070Spatrick case BO_EQ:
429e5dd7070Spatrick case BO_LE:
430e5dd7070Spatrick case BO_GE:
431e5dd7070Spatrick return makeTruthVal(true, resultTy);
432e5dd7070Spatrick case BO_LT:
433e5dd7070Spatrick case BO_GT:
434e5dd7070Spatrick case BO_NE:
435e5dd7070Spatrick return makeTruthVal(false, resultTy);
436e5dd7070Spatrick case BO_Xor:
437e5dd7070Spatrick case BO_Sub:
438e5dd7070Spatrick if (resultTy->isIntegralOrEnumerationType())
439e5dd7070Spatrick return makeIntVal(0, resultTy);
440a9ac8606Spatrick return evalCast(makeIntVal(0, /*isUnsigned=*/false), resultTy,
441a9ac8606Spatrick QualType{});
442e5dd7070Spatrick case BO_Or:
443e5dd7070Spatrick case BO_And:
444a9ac8606Spatrick return evalCast(lhs, resultTy, QualType{});
445e5dd7070Spatrick }
446e5dd7070Spatrick
447*12c85518Srobert while (true) {
448e5dd7070Spatrick switch (lhs.getSubKind()) {
449e5dd7070Spatrick default:
450e5dd7070Spatrick return makeSymExprValNN(op, lhs, rhs, resultTy);
451e5dd7070Spatrick case nonloc::PointerToMemberKind: {
452e5dd7070Spatrick assert(rhs.getSubKind() == nonloc::PointerToMemberKind &&
453e5dd7070Spatrick "Both SVals should have pointer-to-member-type");
454e5dd7070Spatrick auto LPTM = lhs.castAs<nonloc::PointerToMember>(),
455e5dd7070Spatrick RPTM = rhs.castAs<nonloc::PointerToMember>();
456e5dd7070Spatrick auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData();
457e5dd7070Spatrick switch (op) {
458e5dd7070Spatrick case BO_EQ:
459e5dd7070Spatrick return makeTruthVal(LPTMD == RPTMD, resultTy);
460e5dd7070Spatrick case BO_NE:
461e5dd7070Spatrick return makeTruthVal(LPTMD != RPTMD, resultTy);
462e5dd7070Spatrick default:
463e5dd7070Spatrick return UnknownVal();
464e5dd7070Spatrick }
465e5dd7070Spatrick }
466e5dd7070Spatrick case nonloc::LocAsIntegerKind: {
467e5dd7070Spatrick Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc();
468e5dd7070Spatrick switch (rhs.getSubKind()) {
469e5dd7070Spatrick case nonloc::LocAsIntegerKind:
470e5dd7070Spatrick // FIXME: at the moment the implementation
471e5dd7070Spatrick // of modeling "pointers as integers" is not complete.
472e5dd7070Spatrick if (!BinaryOperator::isComparisonOp(op))
473e5dd7070Spatrick return UnknownVal();
474e5dd7070Spatrick return evalBinOpLL(state, op, lhsL,
475e5dd7070Spatrick rhs.castAs<nonloc::LocAsInteger>().getLoc(),
476e5dd7070Spatrick resultTy);
477e5dd7070Spatrick case nonloc::ConcreteIntKind: {
478e5dd7070Spatrick // FIXME: at the moment the implementation
479e5dd7070Spatrick // of modeling "pointers as integers" is not complete.
480e5dd7070Spatrick if (!BinaryOperator::isComparisonOp(op))
481e5dd7070Spatrick return UnknownVal();
482e5dd7070Spatrick // Transform the integer into a location and compare.
483e5dd7070Spatrick // FIXME: This only makes sense for comparisons. If we want to, say,
484e5dd7070Spatrick // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it,
485e5dd7070Spatrick // then pack it back into a LocAsInteger.
486e5dd7070Spatrick llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue();
487e5dd7070Spatrick // If the region has a symbolic base, pay attention to the type; it
488e5dd7070Spatrick // might be coming from a non-default address space. For non-symbolic
489e5dd7070Spatrick // regions it doesn't matter that much because such comparisons would
490e5dd7070Spatrick // most likely evaluate to concrete false anyway. FIXME: We might
491e5dd7070Spatrick // still need to handle the non-comparison case.
492e5dd7070Spatrick if (SymbolRef lSym = lhs.getAsLocSymbol(true))
493e5dd7070Spatrick BasicVals.getAPSIntType(lSym->getType()).apply(i);
494e5dd7070Spatrick else
495e5dd7070Spatrick BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
496e5dd7070Spatrick return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
497e5dd7070Spatrick }
498e5dd7070Spatrick default:
499e5dd7070Spatrick switch (op) {
500e5dd7070Spatrick case BO_EQ:
501e5dd7070Spatrick return makeTruthVal(false, resultTy);
502e5dd7070Spatrick case BO_NE:
503e5dd7070Spatrick return makeTruthVal(true, resultTy);
504e5dd7070Spatrick default:
505e5dd7070Spatrick // This case also handles pointer arithmetic.
506e5dd7070Spatrick return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
507e5dd7070Spatrick }
508e5dd7070Spatrick }
509e5dd7070Spatrick }
510e5dd7070Spatrick case nonloc::ConcreteIntKind: {
511e5dd7070Spatrick llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
512e5dd7070Spatrick
513e5dd7070Spatrick // If we're dealing with two known constants, just perform the operation.
514*12c85518Srobert if (const llvm::APSInt *KnownRHSValue = getConstValue(state, rhs)) {
515e5dd7070Spatrick llvm::APSInt RHSValue = *KnownRHSValue;
516e5dd7070Spatrick if (BinaryOperator::isComparisonOp(op)) {
517e5dd7070Spatrick // We're looking for a type big enough to compare the two values.
518e5dd7070Spatrick // FIXME: This is not correct. char + short will result in a promotion
519e5dd7070Spatrick // to int. Unfortunately we have lost types by this point.
520e5dd7070Spatrick APSIntType CompareType = std::max(APSIntType(LHSValue),
521e5dd7070Spatrick APSIntType(RHSValue));
522e5dd7070Spatrick CompareType.apply(LHSValue);
523e5dd7070Spatrick CompareType.apply(RHSValue);
524e5dd7070Spatrick } else if (!BinaryOperator::isShiftOp(op)) {
525e5dd7070Spatrick APSIntType IntType = BasicVals.getAPSIntType(resultTy);
526e5dd7070Spatrick IntType.apply(LHSValue);
527e5dd7070Spatrick IntType.apply(RHSValue);
528e5dd7070Spatrick }
529e5dd7070Spatrick
530e5dd7070Spatrick const llvm::APSInt *Result =
531e5dd7070Spatrick BasicVals.evalAPSInt(op, LHSValue, RHSValue);
532e5dd7070Spatrick if (!Result)
533e5dd7070Spatrick return UndefinedVal();
534e5dd7070Spatrick
535e5dd7070Spatrick return nonloc::ConcreteInt(*Result);
536e5dd7070Spatrick }
537e5dd7070Spatrick
538e5dd7070Spatrick // Swap the left and right sides and flip the operator if doing so
539e5dd7070Spatrick // allows us to better reason about the expression (this is a form
540e5dd7070Spatrick // of expression canonicalization).
541e5dd7070Spatrick // While we're at it, catch some special cases for non-commutative ops.
542e5dd7070Spatrick switch (op) {
543e5dd7070Spatrick case BO_LT:
544e5dd7070Spatrick case BO_GT:
545e5dd7070Spatrick case BO_LE:
546e5dd7070Spatrick case BO_GE:
547e5dd7070Spatrick op = BinaryOperator::reverseComparisonOp(op);
548*12c85518Srobert [[fallthrough]];
549e5dd7070Spatrick case BO_EQ:
550e5dd7070Spatrick case BO_NE:
551e5dd7070Spatrick case BO_Add:
552e5dd7070Spatrick case BO_Mul:
553e5dd7070Spatrick case BO_And:
554e5dd7070Spatrick case BO_Xor:
555e5dd7070Spatrick case BO_Or:
556e5dd7070Spatrick std::swap(lhs, rhs);
557e5dd7070Spatrick continue;
558e5dd7070Spatrick case BO_Shr:
559e5dd7070Spatrick // (~0)>>a
560*12c85518Srobert if (LHSValue.isAllOnes() && LHSValue.isSigned())
561a9ac8606Spatrick return evalCast(lhs, resultTy, QualType{});
562*12c85518Srobert [[fallthrough]];
563e5dd7070Spatrick case BO_Shl:
564e5dd7070Spatrick // 0<<a and 0>>a
565e5dd7070Spatrick if (LHSValue == 0)
566a9ac8606Spatrick return evalCast(lhs, resultTy, QualType{});
567e5dd7070Spatrick return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
568a9ac8606Spatrick case BO_Div:
569a9ac8606Spatrick // 0 / x == 0
570ec727ea7Spatrick case BO_Rem:
571ec727ea7Spatrick // 0 % x == 0
572ec727ea7Spatrick if (LHSValue == 0)
573ec727ea7Spatrick return makeZeroVal(resultTy);
574*12c85518Srobert [[fallthrough]];
575e5dd7070Spatrick default:
576e5dd7070Spatrick return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
577e5dd7070Spatrick }
578e5dd7070Spatrick }
579e5dd7070Spatrick case nonloc::SymbolValKind: {
580e5dd7070Spatrick // We only handle LHS as simple symbols or SymIntExprs.
581e5dd7070Spatrick SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
582e5dd7070Spatrick
583e5dd7070Spatrick // LHS is a symbolic expression.
584e5dd7070Spatrick if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
585e5dd7070Spatrick
586e5dd7070Spatrick // Is this a logical not? (!x is represented as x == 0.)
587e5dd7070Spatrick if (op == BO_EQ && rhs.isZeroConstant()) {
588e5dd7070Spatrick // We know how to negate certain expressions. Simplify them here.
589e5dd7070Spatrick
590e5dd7070Spatrick BinaryOperator::Opcode opc = symIntExpr->getOpcode();
591e5dd7070Spatrick switch (opc) {
592e5dd7070Spatrick default:
593e5dd7070Spatrick // We don't know how to negate this operation.
594e5dd7070Spatrick // Just handle it as if it were a normal comparison to 0.
595e5dd7070Spatrick break;
596e5dd7070Spatrick case BO_LAnd:
597e5dd7070Spatrick case BO_LOr:
598e5dd7070Spatrick llvm_unreachable("Logical operators handled by branching logic.");
599e5dd7070Spatrick case BO_Assign:
600e5dd7070Spatrick case BO_MulAssign:
601e5dd7070Spatrick case BO_DivAssign:
602e5dd7070Spatrick case BO_RemAssign:
603e5dd7070Spatrick case BO_AddAssign:
604e5dd7070Spatrick case BO_SubAssign:
605e5dd7070Spatrick case BO_ShlAssign:
606e5dd7070Spatrick case BO_ShrAssign:
607e5dd7070Spatrick case BO_AndAssign:
608e5dd7070Spatrick case BO_XorAssign:
609e5dd7070Spatrick case BO_OrAssign:
610e5dd7070Spatrick case BO_Comma:
611e5dd7070Spatrick llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
612e5dd7070Spatrick case BO_PtrMemD:
613e5dd7070Spatrick case BO_PtrMemI:
614e5dd7070Spatrick llvm_unreachable("Pointer arithmetic not handled here.");
615e5dd7070Spatrick case BO_LT:
616e5dd7070Spatrick case BO_GT:
617e5dd7070Spatrick case BO_LE:
618e5dd7070Spatrick case BO_GE:
619e5dd7070Spatrick case BO_EQ:
620e5dd7070Spatrick case BO_NE:
621e5dd7070Spatrick assert(resultTy->isBooleanType() ||
622e5dd7070Spatrick resultTy == getConditionType());
623e5dd7070Spatrick assert(symIntExpr->getType()->isBooleanType() ||
624e5dd7070Spatrick getContext().hasSameUnqualifiedType(symIntExpr->getType(),
625e5dd7070Spatrick getConditionType()));
626e5dd7070Spatrick // Negate the comparison and make a value.
627e5dd7070Spatrick opc = BinaryOperator::negateComparisonOp(opc);
628e5dd7070Spatrick return makeNonLoc(symIntExpr->getLHS(), opc,
629e5dd7070Spatrick symIntExpr->getRHS(), resultTy);
630e5dd7070Spatrick }
631e5dd7070Spatrick }
632e5dd7070Spatrick
633e5dd7070Spatrick // For now, only handle expressions whose RHS is a constant.
634*12c85518Srobert if (const llvm::APSInt *RHSValue = getConstValue(state, rhs)) {
635e5dd7070Spatrick // If both the LHS and the current expression are additive,
636e5dd7070Spatrick // fold their constants and try again.
637e5dd7070Spatrick if (BinaryOperator::isAdditiveOp(op)) {
638e5dd7070Spatrick BinaryOperator::Opcode lop = symIntExpr->getOpcode();
639e5dd7070Spatrick if (BinaryOperator::isAdditiveOp(lop)) {
640e5dd7070Spatrick // Convert the two constants to a common type, then combine them.
641e5dd7070Spatrick
642e5dd7070Spatrick // resultTy may not be the best type to convert to, but it's
643e5dd7070Spatrick // probably the best choice in expressions with mixed type
644e5dd7070Spatrick // (such as x+1U+2LL). The rules for implicit conversions should
645e5dd7070Spatrick // choose a reasonable type to preserve the expression, and will
646e5dd7070Spatrick // at least match how the value is going to be used.
647e5dd7070Spatrick APSIntType IntType = BasicVals.getAPSIntType(resultTy);
648e5dd7070Spatrick const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
649e5dd7070Spatrick const llvm::APSInt &second = IntType.convert(*RHSValue);
650e5dd7070Spatrick
651*12c85518Srobert // If the op and lop agrees, then we just need to
652*12c85518Srobert // sum the constants. Otherwise, we change to operation
653*12c85518Srobert // type if substraction would produce negative value
654*12c85518Srobert // (and cause overflow for unsigned integers),
655*12c85518Srobert // as consequence x+1U-10 produces x-9U, instead
656*12c85518Srobert // of x+4294967287U, that would be produced without this
657*12c85518Srobert // additional check.
658e5dd7070Spatrick const llvm::APSInt *newRHS;
659*12c85518Srobert if (lop == op) {
660e5dd7070Spatrick newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
661*12c85518Srobert } else if (first >= second) {
662e5dd7070Spatrick newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
663*12c85518Srobert op = lop;
664*12c85518Srobert } else {
665*12c85518Srobert newRHS = BasicVals.evalAPSInt(BO_Sub, second, first);
666*12c85518Srobert }
667e5dd7070Spatrick
668e5dd7070Spatrick assert(newRHS && "Invalid operation despite common type!");
669e5dd7070Spatrick rhs = nonloc::ConcreteInt(*newRHS);
670e5dd7070Spatrick lhs = nonloc::SymbolVal(symIntExpr->getLHS());
671e5dd7070Spatrick continue;
672e5dd7070Spatrick }
673e5dd7070Spatrick }
674e5dd7070Spatrick
675e5dd7070Spatrick // Otherwise, make a SymIntExpr out of the expression.
676e5dd7070Spatrick return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
677e5dd7070Spatrick }
678e5dd7070Spatrick }
679e5dd7070Spatrick
680e5dd7070Spatrick // Is the RHS a constant?
681*12c85518Srobert if (const llvm::APSInt *RHSValue = getConstValue(state, rhs))
682e5dd7070Spatrick return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
683e5dd7070Spatrick
684*12c85518Srobert if (std::optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy))
685e5dd7070Spatrick return *V;
686e5dd7070Spatrick
687e5dd7070Spatrick // Give up -- this is not a symbolic expression we can handle.
688e5dd7070Spatrick return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
689e5dd7070Spatrick }
690e5dd7070Spatrick }
691e5dd7070Spatrick }
692e5dd7070Spatrick }
693e5dd7070Spatrick
evalBinOpFieldRegionFieldRegion(const FieldRegion * LeftFR,const FieldRegion * RightFR,BinaryOperator::Opcode op,QualType resultTy,SimpleSValBuilder & SVB)694e5dd7070Spatrick static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR,
695e5dd7070Spatrick const FieldRegion *RightFR,
696e5dd7070Spatrick BinaryOperator::Opcode op,
697e5dd7070Spatrick QualType resultTy,
698e5dd7070Spatrick SimpleSValBuilder &SVB) {
699e5dd7070Spatrick // Only comparisons are meaningful here!
700e5dd7070Spatrick if (!BinaryOperator::isComparisonOp(op))
701e5dd7070Spatrick return UnknownVal();
702e5dd7070Spatrick
703e5dd7070Spatrick // Next, see if the two FRs have the same super-region.
704e5dd7070Spatrick // FIXME: This doesn't handle casts yet, and simply stripping the casts
705e5dd7070Spatrick // doesn't help.
706e5dd7070Spatrick if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
707e5dd7070Spatrick return UnknownVal();
708e5dd7070Spatrick
709e5dd7070Spatrick const FieldDecl *LeftFD = LeftFR->getDecl();
710e5dd7070Spatrick const FieldDecl *RightFD = RightFR->getDecl();
711e5dd7070Spatrick const RecordDecl *RD = LeftFD->getParent();
712e5dd7070Spatrick
713e5dd7070Spatrick // Make sure the two FRs are from the same kind of record. Just in case!
714e5dd7070Spatrick // FIXME: This is probably where inheritance would be a problem.
715e5dd7070Spatrick if (RD != RightFD->getParent())
716e5dd7070Spatrick return UnknownVal();
717e5dd7070Spatrick
718e5dd7070Spatrick // We know for sure that the two fields are not the same, since that
719e5dd7070Spatrick // would have given us the same SVal.
720e5dd7070Spatrick if (op == BO_EQ)
721e5dd7070Spatrick return SVB.makeTruthVal(false, resultTy);
722e5dd7070Spatrick if (op == BO_NE)
723e5dd7070Spatrick return SVB.makeTruthVal(true, resultTy);
724e5dd7070Spatrick
725e5dd7070Spatrick // Iterate through the fields and see which one comes first.
726e5dd7070Spatrick // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
727e5dd7070Spatrick // members and the units in which bit-fields reside have addresses that
728e5dd7070Spatrick // increase in the order in which they are declared."
729e5dd7070Spatrick bool leftFirst = (op == BO_LT || op == BO_LE);
730e5dd7070Spatrick for (const auto *I : RD->fields()) {
731e5dd7070Spatrick if (I == LeftFD)
732e5dd7070Spatrick return SVB.makeTruthVal(leftFirst, resultTy);
733e5dd7070Spatrick if (I == RightFD)
734e5dd7070Spatrick return SVB.makeTruthVal(!leftFirst, resultTy);
735e5dd7070Spatrick }
736e5dd7070Spatrick
737e5dd7070Spatrick llvm_unreachable("Fields not found in parent record's definition");
738e5dd7070Spatrick }
739e5dd7070Spatrick
740*12c85518Srobert // This is used in debug builds only for now because some downstream users
741*12c85518Srobert // may hit this assert in their subsequent merges.
742*12c85518Srobert // There are still places in the analyzer where equal bitwidth Locs
743*12c85518Srobert // are compared, and need to be found and corrected. Recent previous fixes have
744*12c85518Srobert // addressed the known problems of making NULLs with specific bitwidths
745*12c85518Srobert // for Loc comparisons along with deprecation of APIs for the same purpose.
746*12c85518Srobert //
assertEqualBitWidths(ProgramStateRef State,Loc RhsLoc,Loc LhsLoc)747*12c85518Srobert static void assertEqualBitWidths(ProgramStateRef State, Loc RhsLoc,
748*12c85518Srobert Loc LhsLoc) {
749*12c85518Srobert // Implements a "best effort" check for RhsLoc and LhsLoc bit widths
750*12c85518Srobert ASTContext &Ctx = State->getStateManager().getContext();
751*12c85518Srobert uint64_t RhsBitwidth =
752*12c85518Srobert RhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(RhsLoc.getType(Ctx));
753*12c85518Srobert uint64_t LhsBitwidth =
754*12c85518Srobert LhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(LhsLoc.getType(Ctx));
755*12c85518Srobert if (RhsBitwidth && LhsBitwidth &&
756*12c85518Srobert (LhsLoc.getSubKind() == RhsLoc.getSubKind())) {
757*12c85518Srobert assert(RhsBitwidth == LhsBitwidth &&
758*12c85518Srobert "RhsLoc and LhsLoc bitwidth must be same!");
759*12c85518Srobert }
760*12c85518Srobert }
761*12c85518Srobert
762e5dd7070Spatrick // FIXME: all this logic will change if/when we have MemRegion::getLocation().
evalBinOpLL(ProgramStateRef state,BinaryOperator::Opcode op,Loc lhs,Loc rhs,QualType resultTy)763e5dd7070Spatrick SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
764e5dd7070Spatrick BinaryOperator::Opcode op,
765e5dd7070Spatrick Loc lhs, Loc rhs,
766e5dd7070Spatrick QualType resultTy) {
767*12c85518Srobert
768*12c85518Srobert // Assert that bitwidth of lhs and rhs are the same.
769*12c85518Srobert // This can happen if two different address spaces are used,
770*12c85518Srobert // and the bitwidths of the address spaces are different.
771*12c85518Srobert // See LIT case clang/test/Analysis/cstring-checker-addressspace.c
772*12c85518Srobert // FIXME: See comment above in the function assertEqualBitWidths
773*12c85518Srobert assertEqualBitWidths(state, rhs, lhs);
774*12c85518Srobert
775e5dd7070Spatrick // Only comparisons and subtractions are valid operations on two pointers.
776e5dd7070Spatrick // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
777e5dd7070Spatrick // However, if a pointer is casted to an integer, evalBinOpNN may end up
778e5dd7070Spatrick // calling this function with another operation (PR7527). We don't attempt to
779e5dd7070Spatrick // model this for now, but it could be useful, particularly when the
780e5dd7070Spatrick // "location" is actually an integer value that's been passed through a void*.
781e5dd7070Spatrick if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
782e5dd7070Spatrick return UnknownVal();
783e5dd7070Spatrick
784e5dd7070Spatrick // Special cases for when both sides are identical.
785e5dd7070Spatrick if (lhs == rhs) {
786e5dd7070Spatrick switch (op) {
787e5dd7070Spatrick default:
788e5dd7070Spatrick llvm_unreachable("Unimplemented operation for two identical values");
789e5dd7070Spatrick case BO_Sub:
790e5dd7070Spatrick return makeZeroVal(resultTy);
791e5dd7070Spatrick case BO_EQ:
792e5dd7070Spatrick case BO_LE:
793e5dd7070Spatrick case BO_GE:
794e5dd7070Spatrick return makeTruthVal(true, resultTy);
795e5dd7070Spatrick case BO_NE:
796e5dd7070Spatrick case BO_LT:
797e5dd7070Spatrick case BO_GT:
798e5dd7070Spatrick return makeTruthVal(false, resultTy);
799e5dd7070Spatrick }
800e5dd7070Spatrick }
801e5dd7070Spatrick
802e5dd7070Spatrick switch (lhs.getSubKind()) {
803e5dd7070Spatrick default:
804e5dd7070Spatrick llvm_unreachable("Ordering not implemented for this Loc.");
805e5dd7070Spatrick
806e5dd7070Spatrick case loc::GotoLabelKind:
807e5dd7070Spatrick // The only thing we know about labels is that they're non-null.
808e5dd7070Spatrick if (rhs.isZeroConstant()) {
809e5dd7070Spatrick switch (op) {
810e5dd7070Spatrick default:
811e5dd7070Spatrick break;
812e5dd7070Spatrick case BO_Sub:
813a9ac8606Spatrick return evalCast(lhs, resultTy, QualType{});
814e5dd7070Spatrick case BO_EQ:
815e5dd7070Spatrick case BO_LE:
816e5dd7070Spatrick case BO_LT:
817e5dd7070Spatrick return makeTruthVal(false, resultTy);
818e5dd7070Spatrick case BO_NE:
819e5dd7070Spatrick case BO_GT:
820e5dd7070Spatrick case BO_GE:
821e5dd7070Spatrick return makeTruthVal(true, resultTy);
822e5dd7070Spatrick }
823e5dd7070Spatrick }
824e5dd7070Spatrick // There may be two labels for the same location, and a function region may
825e5dd7070Spatrick // have the same address as a label at the start of the function (depending
826e5dd7070Spatrick // on the ABI).
827e5dd7070Spatrick // FIXME: we can probably do a comparison against other MemRegions, though.
828e5dd7070Spatrick // FIXME: is there a way to tell if two labels refer to the same location?
829e5dd7070Spatrick return UnknownVal();
830e5dd7070Spatrick
831e5dd7070Spatrick case loc::ConcreteIntKind: {
832*12c85518Srobert auto L = lhs.castAs<loc::ConcreteInt>();
833*12c85518Srobert
834e5dd7070Spatrick // If one of the operands is a symbol and the other is a constant,
835e5dd7070Spatrick // build an expression for use by the constraint manager.
836e5dd7070Spatrick if (SymbolRef rSym = rhs.getAsLocSymbol()) {
837e5dd7070Spatrick // We can only build expressions with symbols on the left,
838e5dd7070Spatrick // so we need a reversible operator.
839e5dd7070Spatrick if (!BinaryOperator::isComparisonOp(op) || op == BO_Cmp)
840e5dd7070Spatrick return UnknownVal();
841e5dd7070Spatrick
842e5dd7070Spatrick op = BinaryOperator::reverseComparisonOp(op);
843*12c85518Srobert return makeNonLoc(rSym, op, L.getValue(), resultTy);
844e5dd7070Spatrick }
845e5dd7070Spatrick
846e5dd7070Spatrick // If both operands are constants, just perform the operation.
847*12c85518Srobert if (std::optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
848*12c85518Srobert assert(BinaryOperator::isComparisonOp(op) || op == BO_Sub);
849e5dd7070Spatrick
850*12c85518Srobert if (const auto *ResultInt =
851*12c85518Srobert BasicVals.evalAPSInt(op, L.getValue(), rInt->getValue()))
852*12c85518Srobert return evalCast(nonloc::ConcreteInt(*ResultInt), resultTy, QualType{});
853e5dd7070Spatrick return UnknownVal();
854e5dd7070Spatrick }
855e5dd7070Spatrick
856e5dd7070Spatrick // Special case comparisons against NULL.
857e5dd7070Spatrick // This must come after the test if the RHS is a symbol, which is used to
858e5dd7070Spatrick // build constraints. The address of any non-symbolic region is guaranteed
859e5dd7070Spatrick // to be non-NULL, as is any label.
860*12c85518Srobert assert((isa<loc::MemRegionVal, loc::GotoLabel>(rhs)));
861e5dd7070Spatrick if (lhs.isZeroConstant()) {
862e5dd7070Spatrick switch (op) {
863e5dd7070Spatrick default:
864e5dd7070Spatrick break;
865e5dd7070Spatrick case BO_EQ:
866e5dd7070Spatrick case BO_GT:
867e5dd7070Spatrick case BO_GE:
868e5dd7070Spatrick return makeTruthVal(false, resultTy);
869e5dd7070Spatrick case BO_NE:
870e5dd7070Spatrick case BO_LT:
871e5dd7070Spatrick case BO_LE:
872e5dd7070Spatrick return makeTruthVal(true, resultTy);
873e5dd7070Spatrick }
874e5dd7070Spatrick }
875e5dd7070Spatrick
876e5dd7070Spatrick // Comparing an arbitrary integer to a region or label address is
877e5dd7070Spatrick // completely unknowable.
878e5dd7070Spatrick return UnknownVal();
879e5dd7070Spatrick }
880e5dd7070Spatrick case loc::MemRegionValKind: {
881*12c85518Srobert if (std::optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
882e5dd7070Spatrick // If one of the operands is a symbol and the other is a constant,
883e5dd7070Spatrick // build an expression for use by the constraint manager.
884e5dd7070Spatrick if (SymbolRef lSym = lhs.getAsLocSymbol(true)) {
885e5dd7070Spatrick if (BinaryOperator::isComparisonOp(op))
886e5dd7070Spatrick return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
887e5dd7070Spatrick return UnknownVal();
888e5dd7070Spatrick }
889e5dd7070Spatrick // Special case comparisons to NULL.
890e5dd7070Spatrick // This must come after the test if the LHS is a symbol, which is used to
891e5dd7070Spatrick // build constraints. The address of any non-symbolic region is guaranteed
892e5dd7070Spatrick // to be non-NULL.
893e5dd7070Spatrick if (rInt->isZeroConstant()) {
894e5dd7070Spatrick if (op == BO_Sub)
895a9ac8606Spatrick return evalCast(lhs, resultTy, QualType{});
896e5dd7070Spatrick
897e5dd7070Spatrick if (BinaryOperator::isComparisonOp(op)) {
898e5dd7070Spatrick QualType boolType = getContext().BoolTy;
899a9ac8606Spatrick NonLoc l = evalCast(lhs, boolType, QualType{}).castAs<NonLoc>();
900e5dd7070Spatrick NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>();
901e5dd7070Spatrick return evalBinOpNN(state, op, l, r, resultTy);
902e5dd7070Spatrick }
903e5dd7070Spatrick }
904e5dd7070Spatrick
905e5dd7070Spatrick // Comparing a region to an arbitrary integer is completely unknowable.
906e5dd7070Spatrick return UnknownVal();
907e5dd7070Spatrick }
908e5dd7070Spatrick
909e5dd7070Spatrick // Get both values as regions, if possible.
910e5dd7070Spatrick const MemRegion *LeftMR = lhs.getAsRegion();
911e5dd7070Spatrick assert(LeftMR && "MemRegionValKind SVal doesn't have a region!");
912e5dd7070Spatrick
913e5dd7070Spatrick const MemRegion *RightMR = rhs.getAsRegion();
914e5dd7070Spatrick if (!RightMR)
915e5dd7070Spatrick // The RHS is probably a label, which in theory could address a region.
916e5dd7070Spatrick // FIXME: we can probably make a more useful statement about non-code
917e5dd7070Spatrick // regions, though.
918e5dd7070Spatrick return UnknownVal();
919e5dd7070Spatrick
920e5dd7070Spatrick const MemRegion *LeftBase = LeftMR->getBaseRegion();
921e5dd7070Spatrick const MemRegion *RightBase = RightMR->getBaseRegion();
922e5dd7070Spatrick const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
923e5dd7070Spatrick const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
924e5dd7070Spatrick const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
925e5dd7070Spatrick
926e5dd7070Spatrick // If the two regions are from different known memory spaces they cannot be
927e5dd7070Spatrick // equal. Also, assume that no symbolic region (whose memory space is
928e5dd7070Spatrick // unknown) is on the stack.
929e5dd7070Spatrick if (LeftMS != RightMS &&
930e5dd7070Spatrick ((LeftMS != UnknownMS && RightMS != UnknownMS) ||
931e5dd7070Spatrick (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
932e5dd7070Spatrick switch (op) {
933e5dd7070Spatrick default:
934e5dd7070Spatrick return UnknownVal();
935e5dd7070Spatrick case BO_EQ:
936e5dd7070Spatrick return makeTruthVal(false, resultTy);
937e5dd7070Spatrick case BO_NE:
938e5dd7070Spatrick return makeTruthVal(true, resultTy);
939e5dd7070Spatrick }
940e5dd7070Spatrick }
941e5dd7070Spatrick
942e5dd7070Spatrick // If both values wrap regions, see if they're from different base regions.
943e5dd7070Spatrick // Note, heap base symbolic regions are assumed to not alias with
944e5dd7070Spatrick // each other; for example, we assume that malloc returns different address
945e5dd7070Spatrick // on each invocation.
946e5dd7070Spatrick // FIXME: ObjC object pointers always reside on the heap, but currently
947e5dd7070Spatrick // we treat their memory space as unknown, because symbolic pointers
948e5dd7070Spatrick // to ObjC objects may alias. There should be a way to construct
949e5dd7070Spatrick // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker
950e5dd7070Spatrick // guesses memory space for ObjC object pointers manually instead of
951e5dd7070Spatrick // relying on us.
952e5dd7070Spatrick if (LeftBase != RightBase &&
953e5dd7070Spatrick ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
954e5dd7070Spatrick (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
955e5dd7070Spatrick switch (op) {
956e5dd7070Spatrick default:
957e5dd7070Spatrick return UnknownVal();
958e5dd7070Spatrick case BO_EQ:
959e5dd7070Spatrick return makeTruthVal(false, resultTy);
960e5dd7070Spatrick case BO_NE:
961e5dd7070Spatrick return makeTruthVal(true, resultTy);
962e5dd7070Spatrick }
963e5dd7070Spatrick }
964e5dd7070Spatrick
965e5dd7070Spatrick // Handle special cases for when both regions are element regions.
966e5dd7070Spatrick const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
967e5dd7070Spatrick const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR);
968e5dd7070Spatrick if (RightER && LeftER) {
969e5dd7070Spatrick // Next, see if the two ERs have the same super-region and matching types.
970e5dd7070Spatrick // FIXME: This should do something useful even if the types don't match,
971e5dd7070Spatrick // though if both indexes are constant the RegionRawOffset path will
972e5dd7070Spatrick // give the correct answer.
973e5dd7070Spatrick if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
974e5dd7070Spatrick LeftER->getElementType() == RightER->getElementType()) {
975e5dd7070Spatrick // Get the left index and cast it to the correct type.
976e5dd7070Spatrick // If the index is unknown or undefined, bail out here.
977e5dd7070Spatrick SVal LeftIndexVal = LeftER->getIndex();
978*12c85518Srobert std::optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
979e5dd7070Spatrick if (!LeftIndex)
980e5dd7070Spatrick return UnknownVal();
981a9ac8606Spatrick LeftIndexVal = evalCast(*LeftIndex, ArrayIndexTy, QualType{});
982e5dd7070Spatrick LeftIndex = LeftIndexVal.getAs<NonLoc>();
983e5dd7070Spatrick if (!LeftIndex)
984e5dd7070Spatrick return UnknownVal();
985e5dd7070Spatrick
986e5dd7070Spatrick // Do the same for the right index.
987e5dd7070Spatrick SVal RightIndexVal = RightER->getIndex();
988*12c85518Srobert std::optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
989e5dd7070Spatrick if (!RightIndex)
990e5dd7070Spatrick return UnknownVal();
991a9ac8606Spatrick RightIndexVal = evalCast(*RightIndex, ArrayIndexTy, QualType{});
992e5dd7070Spatrick RightIndex = RightIndexVal.getAs<NonLoc>();
993e5dd7070Spatrick if (!RightIndex)
994e5dd7070Spatrick return UnknownVal();
995e5dd7070Spatrick
996e5dd7070Spatrick // Actually perform the operation.
997e5dd7070Spatrick // evalBinOpNN expects the two indexes to already be the right type.
998e5dd7070Spatrick return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
999e5dd7070Spatrick }
1000e5dd7070Spatrick }
1001e5dd7070Spatrick
1002e5dd7070Spatrick // Special handling of the FieldRegions, even with symbolic offsets.
1003e5dd7070Spatrick const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
1004e5dd7070Spatrick const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR);
1005e5dd7070Spatrick if (RightFR && LeftFR) {
1006e5dd7070Spatrick SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy,
1007e5dd7070Spatrick *this);
1008e5dd7070Spatrick if (!R.isUnknown())
1009e5dd7070Spatrick return R;
1010e5dd7070Spatrick }
1011e5dd7070Spatrick
1012e5dd7070Spatrick // Compare the regions using the raw offsets.
1013e5dd7070Spatrick RegionOffset LeftOffset = LeftMR->getAsOffset();
1014e5dd7070Spatrick RegionOffset RightOffset = RightMR->getAsOffset();
1015e5dd7070Spatrick
1016e5dd7070Spatrick if (LeftOffset.getRegion() != nullptr &&
1017e5dd7070Spatrick LeftOffset.getRegion() == RightOffset.getRegion() &&
1018e5dd7070Spatrick !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) {
1019e5dd7070Spatrick int64_t left = LeftOffset.getOffset();
1020e5dd7070Spatrick int64_t right = RightOffset.getOffset();
1021e5dd7070Spatrick
1022e5dd7070Spatrick switch (op) {
1023e5dd7070Spatrick default:
1024e5dd7070Spatrick return UnknownVal();
1025e5dd7070Spatrick case BO_LT:
1026e5dd7070Spatrick return makeTruthVal(left < right, resultTy);
1027e5dd7070Spatrick case BO_GT:
1028e5dd7070Spatrick return makeTruthVal(left > right, resultTy);
1029e5dd7070Spatrick case BO_LE:
1030e5dd7070Spatrick return makeTruthVal(left <= right, resultTy);
1031e5dd7070Spatrick case BO_GE:
1032e5dd7070Spatrick return makeTruthVal(left >= right, resultTy);
1033e5dd7070Spatrick case BO_EQ:
1034e5dd7070Spatrick return makeTruthVal(left == right, resultTy);
1035e5dd7070Spatrick case BO_NE:
1036e5dd7070Spatrick return makeTruthVal(left != right, resultTy);
1037e5dd7070Spatrick }
1038e5dd7070Spatrick }
1039e5dd7070Spatrick
1040e5dd7070Spatrick // At this point we're not going to get a good answer, but we can try
1041e5dd7070Spatrick // conjuring an expression instead.
1042e5dd7070Spatrick SymbolRef LHSSym = lhs.getAsLocSymbol();
1043e5dd7070Spatrick SymbolRef RHSSym = rhs.getAsLocSymbol();
1044e5dd7070Spatrick if (LHSSym && RHSSym)
1045e5dd7070Spatrick return makeNonLoc(LHSSym, op, RHSSym, resultTy);
1046e5dd7070Spatrick
1047e5dd7070Spatrick // If we get here, we have no way of comparing the regions.
1048e5dd7070Spatrick return UnknownVal();
1049e5dd7070Spatrick }
1050e5dd7070Spatrick }
1051e5dd7070Spatrick }
1052e5dd7070Spatrick
evalBinOpLN(ProgramStateRef state,BinaryOperator::Opcode op,Loc lhs,NonLoc rhs,QualType resultTy)1053e5dd7070Spatrick SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
1054a9ac8606Spatrick BinaryOperator::Opcode op, Loc lhs,
1055a9ac8606Spatrick NonLoc rhs, QualType resultTy) {
1056e5dd7070Spatrick if (op >= BO_PtrMemD && op <= BO_PtrMemI) {
1057e5dd7070Spatrick if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) {
1058e5dd7070Spatrick if (PTMSV->isNullMemberPointer())
1059e5dd7070Spatrick return UndefinedVal();
1060a9ac8606Spatrick
1061a9ac8606Spatrick auto getFieldLValue = [&](const auto *FD) -> SVal {
1062e5dd7070Spatrick SVal Result = lhs;
1063e5dd7070Spatrick
1064e5dd7070Spatrick for (const auto &I : *PTMSV)
1065e5dd7070Spatrick Result = StateMgr.getStoreManager().evalDerivedToBase(
1066e5dd7070Spatrick Result, I->getType(), I->isVirtual());
1067a9ac8606Spatrick
1068e5dd7070Spatrick return state->getLValue(FD, Result);
1069a9ac8606Spatrick };
1070a9ac8606Spatrick
1071a9ac8606Spatrick if (const auto *FD = PTMSV->getDeclAs<FieldDecl>()) {
1072a9ac8606Spatrick return getFieldLValue(FD);
1073a9ac8606Spatrick }
1074a9ac8606Spatrick if (const auto *FD = PTMSV->getDeclAs<IndirectFieldDecl>()) {
1075a9ac8606Spatrick return getFieldLValue(FD);
1076e5dd7070Spatrick }
1077e5dd7070Spatrick }
1078e5dd7070Spatrick
1079e5dd7070Spatrick return rhs;
1080e5dd7070Spatrick }
1081e5dd7070Spatrick
1082e5dd7070Spatrick assert(!BinaryOperator::isComparisonOp(op) &&
1083e5dd7070Spatrick "arguments to comparison ops must be of the same type");
1084e5dd7070Spatrick
1085e5dd7070Spatrick // Special case: rhs is a zero constant.
1086e5dd7070Spatrick if (rhs.isZeroConstant())
1087e5dd7070Spatrick return lhs;
1088e5dd7070Spatrick
1089e5dd7070Spatrick // Perserve the null pointer so that it can be found by the DerefChecker.
1090e5dd7070Spatrick if (lhs.isZeroConstant())
1091e5dd7070Spatrick return lhs;
1092e5dd7070Spatrick
1093e5dd7070Spatrick // We are dealing with pointer arithmetic.
1094e5dd7070Spatrick
1095e5dd7070Spatrick // Handle pointer arithmetic on constant values.
1096*12c85518Srobert if (std::optional<nonloc::ConcreteInt> rhsInt =
1097*12c85518Srobert rhs.getAs<nonloc::ConcreteInt>()) {
1098*12c85518Srobert if (std::optional<loc::ConcreteInt> lhsInt =
1099*12c85518Srobert lhs.getAs<loc::ConcreteInt>()) {
1100e5dd7070Spatrick const llvm::APSInt &leftI = lhsInt->getValue();
1101e5dd7070Spatrick assert(leftI.isUnsigned());
1102e5dd7070Spatrick llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
1103e5dd7070Spatrick
1104e5dd7070Spatrick // Convert the bitwidth of rightI. This should deal with overflow
1105e5dd7070Spatrick // since we are dealing with concrete values.
1106e5dd7070Spatrick rightI = rightI.extOrTrunc(leftI.getBitWidth());
1107e5dd7070Spatrick
1108e5dd7070Spatrick // Offset the increment by the pointer size.
1109e5dd7070Spatrick llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
1110e5dd7070Spatrick QualType pointeeType = resultTy->getPointeeType();
1111e5dd7070Spatrick Multiplicand = getContext().getTypeSizeInChars(pointeeType).getQuantity();
1112e5dd7070Spatrick rightI *= Multiplicand;
1113e5dd7070Spatrick
1114e5dd7070Spatrick // Compute the adjusted pointer.
1115e5dd7070Spatrick switch (op) {
1116e5dd7070Spatrick case BO_Add:
1117e5dd7070Spatrick rightI = leftI + rightI;
1118e5dd7070Spatrick break;
1119e5dd7070Spatrick case BO_Sub:
1120e5dd7070Spatrick rightI = leftI - rightI;
1121e5dd7070Spatrick break;
1122e5dd7070Spatrick default:
1123e5dd7070Spatrick llvm_unreachable("Invalid pointer arithmetic operation");
1124e5dd7070Spatrick }
1125e5dd7070Spatrick return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
1126e5dd7070Spatrick }
1127e5dd7070Spatrick }
1128e5dd7070Spatrick
1129e5dd7070Spatrick // Handle cases where 'lhs' is a region.
1130e5dd7070Spatrick if (const MemRegion *region = lhs.getAsRegion()) {
1131e5dd7070Spatrick rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
1132e5dd7070Spatrick SVal index = UnknownVal();
1133e5dd7070Spatrick const SubRegion *superR = nullptr;
1134e5dd7070Spatrick // We need to know the type of the pointer in order to add an integer to it.
1135e5dd7070Spatrick // Depending on the type, different amount of bytes is added.
1136e5dd7070Spatrick QualType elementType;
1137e5dd7070Spatrick
1138e5dd7070Spatrick if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
1139e5dd7070Spatrick assert(op == BO_Add || op == BO_Sub);
1140e5dd7070Spatrick index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
1141e5dd7070Spatrick getArrayIndexType());
1142e5dd7070Spatrick superR = cast<SubRegion>(elemReg->getSuperRegion());
1143e5dd7070Spatrick elementType = elemReg->getElementType();
1144e5dd7070Spatrick }
1145e5dd7070Spatrick else if (isa<SubRegion>(region)) {
1146e5dd7070Spatrick assert(op == BO_Add || op == BO_Sub);
1147e5dd7070Spatrick index = (op == BO_Add) ? rhs : evalMinus(rhs);
1148e5dd7070Spatrick superR = cast<SubRegion>(region);
1149e5dd7070Spatrick // TODO: Is this actually reliable? Maybe improving our MemRegion
1150e5dd7070Spatrick // hierarchy to provide typed regions for all non-void pointers would be
1151e5dd7070Spatrick // better. For instance, we cannot extend this towards LocAsInteger
1152e5dd7070Spatrick // operations, where result type of the expression is integer.
1153e5dd7070Spatrick if (resultTy->isAnyPointerType())
1154e5dd7070Spatrick elementType = resultTy->getPointeeType();
1155e5dd7070Spatrick }
1156e5dd7070Spatrick
1157e5dd7070Spatrick // Represent arithmetic on void pointers as arithmetic on char pointers.
1158e5dd7070Spatrick // It is fine when a TypedValueRegion of char value type represents
1159e5dd7070Spatrick // a void pointer. Note that arithmetic on void pointers is a GCC extension.
1160e5dd7070Spatrick if (elementType->isVoidType())
1161e5dd7070Spatrick elementType = getContext().CharTy;
1162e5dd7070Spatrick
1163*12c85518Srobert if (std::optional<NonLoc> indexV = index.getAs<NonLoc>()) {
1164e5dd7070Spatrick return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
1165e5dd7070Spatrick superR, getContext()));
1166e5dd7070Spatrick }
1167e5dd7070Spatrick }
1168e5dd7070Spatrick return UnknownVal();
1169e5dd7070Spatrick }
1170e5dd7070Spatrick
getConstValue(ProgramStateRef state,SVal V)1171*12c85518Srobert const llvm::APSInt *SimpleSValBuilder::getConstValue(ProgramStateRef state,
1172e5dd7070Spatrick SVal V) {
1173e5dd7070Spatrick if (V.isUnknownOrUndef())
1174e5dd7070Spatrick return nullptr;
1175e5dd7070Spatrick
1176*12c85518Srobert if (std::optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
1177e5dd7070Spatrick return &X->getValue();
1178e5dd7070Spatrick
1179*12c85518Srobert if (std::optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
1180e5dd7070Spatrick return &X->getValue();
1181e5dd7070Spatrick
1182e5dd7070Spatrick if (SymbolRef Sym = V.getAsSymbol())
1183e5dd7070Spatrick return state->getConstraintManager().getSymVal(state, Sym);
1184e5dd7070Spatrick
1185e5dd7070Spatrick return nullptr;
1186e5dd7070Spatrick }
1187e5dd7070Spatrick
getKnownValue(ProgramStateRef state,SVal V)1188*12c85518Srobert const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
1189*12c85518Srobert SVal V) {
1190*12c85518Srobert return getConstValue(state, simplifySVal(state, V));
1191*12c85518Srobert }
1192*12c85518Srobert
simplifyUntilFixpoint(ProgramStateRef State,SVal Val)1193*12c85518Srobert SVal SimpleSValBuilder::simplifyUntilFixpoint(ProgramStateRef State, SVal Val) {
1194*12c85518Srobert SVal SimplifiedVal = simplifySValOnce(State, Val);
1195*12c85518Srobert while (SimplifiedVal != Val) {
1196*12c85518Srobert Val = SimplifiedVal;
1197*12c85518Srobert SimplifiedVal = simplifySValOnce(State, Val);
1198*12c85518Srobert }
1199*12c85518Srobert return SimplifiedVal;
1200*12c85518Srobert }
1201*12c85518Srobert
simplifySVal(ProgramStateRef State,SVal V)1202e5dd7070Spatrick SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) {
1203*12c85518Srobert return simplifyUntilFixpoint(State, V);
1204*12c85518Srobert }
1205*12c85518Srobert
simplifySValOnce(ProgramStateRef State,SVal V)1206*12c85518Srobert SVal SimpleSValBuilder::simplifySValOnce(ProgramStateRef State, SVal V) {
1207e5dd7070Spatrick // For now, this function tries to constant-fold symbols inside a
1208e5dd7070Spatrick // nonloc::SymbolVal, and does nothing else. More simplifications should
1209e5dd7070Spatrick // be possible, such as constant-folding an index in an ElementRegion.
1210e5dd7070Spatrick
1211e5dd7070Spatrick class Simplifier : public FullSValVisitor<Simplifier, SVal> {
1212e5dd7070Spatrick ProgramStateRef State;
1213e5dd7070Spatrick SValBuilder &SVB;
1214e5dd7070Spatrick
1215e5dd7070Spatrick // Cache results for the lifetime of the Simplifier. Results change every
1216e5dd7070Spatrick // time new constraints are added to the program state, which is the whole
1217e5dd7070Spatrick // point of simplifying, and for that very reason it's pointless to maintain
1218e5dd7070Spatrick // the same cache for the duration of the whole analysis.
1219e5dd7070Spatrick llvm::DenseMap<SymbolRef, SVal> Cached;
1220e5dd7070Spatrick
1221e5dd7070Spatrick static bool isUnchanged(SymbolRef Sym, SVal Val) {
1222e5dd7070Spatrick return Sym == Val.getAsSymbol();
1223e5dd7070Spatrick }
1224e5dd7070Spatrick
1225e5dd7070Spatrick SVal cache(SymbolRef Sym, SVal V) {
1226e5dd7070Spatrick Cached[Sym] = V;
1227e5dd7070Spatrick return V;
1228e5dd7070Spatrick }
1229e5dd7070Spatrick
1230e5dd7070Spatrick SVal skip(SymbolRef Sym) {
1231e5dd7070Spatrick return cache(Sym, SVB.makeSymbolVal(Sym));
1232e5dd7070Spatrick }
1233e5dd7070Spatrick
1234*12c85518Srobert // Return the known const value for the Sym if available, or return Undef
1235*12c85518Srobert // otherwise.
1236*12c85518Srobert SVal getConst(SymbolRef Sym) {
1237*12c85518Srobert const llvm::APSInt *Const =
1238*12c85518Srobert State->getConstraintManager().getSymVal(State, Sym);
1239*12c85518Srobert if (Const)
1240*12c85518Srobert return Loc::isLocType(Sym->getType()) ? (SVal)SVB.makeIntLocVal(*Const)
1241*12c85518Srobert : (SVal)SVB.makeIntVal(*Const);
1242*12c85518Srobert return UndefinedVal();
1243*12c85518Srobert }
1244*12c85518Srobert
1245*12c85518Srobert SVal getConstOrVisit(SymbolRef Sym) {
1246*12c85518Srobert const SVal Ret = getConst(Sym);
1247*12c85518Srobert if (Ret.isUndef())
1248*12c85518Srobert return Visit(Sym);
1249*12c85518Srobert return Ret;
1250*12c85518Srobert }
1251*12c85518Srobert
1252e5dd7070Spatrick public:
1253e5dd7070Spatrick Simplifier(ProgramStateRef State)
1254e5dd7070Spatrick : State(State), SVB(State->getStateManager().getSValBuilder()) {}
1255e5dd7070Spatrick
1256e5dd7070Spatrick SVal VisitSymbolData(const SymbolData *S) {
1257e5dd7070Spatrick // No cache here.
1258e5dd7070Spatrick if (const llvm::APSInt *I =
1259*12c85518Srobert State->getConstraintManager().getSymVal(State, S))
1260e5dd7070Spatrick return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I)
1261e5dd7070Spatrick : (SVal)SVB.makeIntVal(*I);
1262e5dd7070Spatrick return SVB.makeSymbolVal(S);
1263e5dd7070Spatrick }
1264e5dd7070Spatrick
1265e5dd7070Spatrick SVal VisitSymIntExpr(const SymIntExpr *S) {
1266e5dd7070Spatrick auto I = Cached.find(S);
1267e5dd7070Spatrick if (I != Cached.end())
1268e5dd7070Spatrick return I->second;
1269e5dd7070Spatrick
1270*12c85518Srobert SVal LHS = getConstOrVisit(S->getLHS());
1271e5dd7070Spatrick if (isUnchanged(S->getLHS(), LHS))
1272e5dd7070Spatrick return skip(S);
1273e5dd7070Spatrick
1274e5dd7070Spatrick SVal RHS;
1275e5dd7070Spatrick // By looking at the APSInt in the right-hand side of S, we cannot
1276e5dd7070Spatrick // figure out if it should be treated as a Loc or as a NonLoc.
1277e5dd7070Spatrick // So make our guess by recalling that we cannot multiply pointers
1278e5dd7070Spatrick // or compare a pointer to an integer.
1279e5dd7070Spatrick if (Loc::isLocType(S->getLHS()->getType()) &&
1280e5dd7070Spatrick BinaryOperator::isComparisonOp(S->getOpcode())) {
1281e5dd7070Spatrick // The usual conversion of $sym to &SymRegion{$sym}, as they have
1282e5dd7070Spatrick // the same meaning for Loc-type symbols, but the latter form
1283e5dd7070Spatrick // is preferred in SVal computations for being Loc itself.
1284e5dd7070Spatrick if (SymbolRef Sym = LHS.getAsSymbol()) {
1285e5dd7070Spatrick assert(Loc::isLocType(Sym->getType()));
1286e5dd7070Spatrick LHS = SVB.makeLoc(Sym);
1287e5dd7070Spatrick }
1288e5dd7070Spatrick RHS = SVB.makeIntLocVal(S->getRHS());
1289e5dd7070Spatrick } else {
1290e5dd7070Spatrick RHS = SVB.makeIntVal(S->getRHS());
1291e5dd7070Spatrick }
1292e5dd7070Spatrick
1293e5dd7070Spatrick return cache(
1294e5dd7070Spatrick S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
1295e5dd7070Spatrick }
1296e5dd7070Spatrick
1297*12c85518Srobert SVal VisitIntSymExpr(const IntSymExpr *S) {
1298*12c85518Srobert auto I = Cached.find(S);
1299*12c85518Srobert if (I != Cached.end())
1300*12c85518Srobert return I->second;
1301*12c85518Srobert
1302*12c85518Srobert SVal RHS = getConstOrVisit(S->getRHS());
1303*12c85518Srobert if (isUnchanged(S->getRHS(), RHS))
1304*12c85518Srobert return skip(S);
1305*12c85518Srobert
1306*12c85518Srobert SVal LHS = SVB.makeIntVal(S->getLHS());
1307*12c85518Srobert return cache(
1308*12c85518Srobert S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
1309*12c85518Srobert }
1310*12c85518Srobert
1311e5dd7070Spatrick SVal VisitSymSymExpr(const SymSymExpr *S) {
1312e5dd7070Spatrick auto I = Cached.find(S);
1313e5dd7070Spatrick if (I != Cached.end())
1314e5dd7070Spatrick return I->second;
1315e5dd7070Spatrick
1316e5dd7070Spatrick // For now don't try to simplify mixed Loc/NonLoc expressions
1317e5dd7070Spatrick // because they often appear from LocAsInteger operations
1318e5dd7070Spatrick // and we don't know how to combine a LocAsInteger
1319e5dd7070Spatrick // with a concrete value.
1320e5dd7070Spatrick if (Loc::isLocType(S->getLHS()->getType()) !=
1321e5dd7070Spatrick Loc::isLocType(S->getRHS()->getType()))
1322e5dd7070Spatrick return skip(S);
1323e5dd7070Spatrick
1324*12c85518Srobert SVal LHS = getConstOrVisit(S->getLHS());
1325*12c85518Srobert SVal RHS = getConstOrVisit(S->getRHS());
1326*12c85518Srobert
1327e5dd7070Spatrick if (isUnchanged(S->getLHS(), LHS) && isUnchanged(S->getRHS(), RHS))
1328e5dd7070Spatrick return skip(S);
1329e5dd7070Spatrick
1330e5dd7070Spatrick return cache(
1331e5dd7070Spatrick S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
1332e5dd7070Spatrick }
1333e5dd7070Spatrick
1334*12c85518Srobert SVal VisitSymbolCast(const SymbolCast *S) {
1335*12c85518Srobert auto I = Cached.find(S);
1336*12c85518Srobert if (I != Cached.end())
1337*12c85518Srobert return I->second;
1338*12c85518Srobert const SymExpr *OpSym = S->getOperand();
1339*12c85518Srobert SVal OpVal = getConstOrVisit(OpSym);
1340*12c85518Srobert if (isUnchanged(OpSym, OpVal))
1341*12c85518Srobert return skip(S);
1342*12c85518Srobert
1343*12c85518Srobert return cache(S, SVB.evalCast(OpVal, S->getType(), OpSym->getType()));
1344*12c85518Srobert }
1345*12c85518Srobert
1346*12c85518Srobert SVal VisitUnarySymExpr(const UnarySymExpr *S) {
1347*12c85518Srobert auto I = Cached.find(S);
1348*12c85518Srobert if (I != Cached.end())
1349*12c85518Srobert return I->second;
1350*12c85518Srobert SVal Op = getConstOrVisit(S->getOperand());
1351*12c85518Srobert if (isUnchanged(S->getOperand(), Op))
1352*12c85518Srobert return skip(S);
1353*12c85518Srobert
1354*12c85518Srobert return cache(
1355*12c85518Srobert S, SVB.evalUnaryOp(State, S->getOpcode(), Op, S->getType()));
1356*12c85518Srobert }
1357*12c85518Srobert
1358e5dd7070Spatrick SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); }
1359e5dd7070Spatrick
1360e5dd7070Spatrick SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); }
1361e5dd7070Spatrick
1362e5dd7070Spatrick SVal VisitNonLocSymbolVal(nonloc::SymbolVal V) {
1363e5dd7070Spatrick // Simplification is much more costly than computing complexity.
1364e5dd7070Spatrick // For high complexity, it may be not worth it.
1365e5dd7070Spatrick return Visit(V.getSymbol());
1366e5dd7070Spatrick }
1367e5dd7070Spatrick
1368e5dd7070Spatrick SVal VisitSVal(SVal V) { return V; }
1369e5dd7070Spatrick };
1370e5dd7070Spatrick
1371e5dd7070Spatrick SVal SimplifiedV = Simplifier(State).Visit(V);
1372e5dd7070Spatrick return SimplifiedV;
1373e5dd7070Spatrick }
1374