1fa0734ecSArgyrios Kyrtzidis // SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- C++ -*-
2fa0734ecSArgyrios Kyrtzidis //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6fa0734ecSArgyrios Kyrtzidis //
7fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
8fa0734ecSArgyrios Kyrtzidis //
9fa0734ecSArgyrios Kyrtzidis // This file defines SimpleSValBuilder, a basic implementation of SValBuilder.
10fa0734ecSArgyrios Kyrtzidis //
11fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
12fa0734ecSArgyrios Kyrtzidis
13f8cbac4bSTed Kremenek #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
143a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
15d70ec366SAdam Balogh #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
16001fd5b4STed Kremenek #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
1712294f8dSArtem Dergachev #include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h"
18fa0734ecSArgyrios Kyrtzidis
19fa0734ecSArgyrios Kyrtzidis using namespace clang;
20fa0734ecSArgyrios Kyrtzidis using namespace ento;
21fa0734ecSArgyrios Kyrtzidis
22fa0734ecSArgyrios Kyrtzidis namespace {
23fa0734ecSArgyrios Kyrtzidis class SimpleSValBuilder : public SValBuilder {
24978431e8SGabor Marton
25bc2c759aSGabor Marton // Query the constraint manager whether the SVal has only one possible
26bc2c759aSGabor Marton // (integer) value. If that is the case, the value is returned. Otherwise,
27bc2c759aSGabor Marton // returns NULL.
28bc2c759aSGabor Marton // This is an implementation detail. Checkers should use `getKnownValue()`
29bc2c759aSGabor Marton // instead.
30bc2c759aSGabor Marton const llvm::APSInt *getConstValue(ProgramStateRef state, SVal V);
31bc2c759aSGabor Marton
32978431e8SGabor Marton // With one `simplifySValOnce` call, a compound symbols might collapse to
33978431e8SGabor Marton // simpler symbol tree that is still possible to further simplify. Thus, we
34978431e8SGabor Marton // do the simplification on a new symbol tree until we reach the simplest
35978431e8SGabor Marton // form, i.e. the fixpoint.
36978431e8SGabor Marton // Consider the following symbol `(b * b) * b * b` which has this tree:
37978431e8SGabor Marton // *
38978431e8SGabor Marton // / \
39978431e8SGabor Marton // * b
40978431e8SGabor Marton // / \
41978431e8SGabor Marton // / b
42978431e8SGabor Marton // (b * b)
43978431e8SGabor Marton // Now, if the `b * b == 1` new constraint is added then during the first
44978431e8SGabor Marton // iteration we have the following transformations:
45978431e8SGabor Marton // * *
46978431e8SGabor Marton // / \ / \
47978431e8SGabor Marton // * b --> b b
48978431e8SGabor Marton // / \
49978431e8SGabor Marton // / b
50978431e8SGabor Marton // 1
51978431e8SGabor Marton // We need another iteration to reach the final result `1`.
52978431e8SGabor Marton SVal simplifyUntilFixpoint(ProgramStateRef State, SVal Val);
53978431e8SGabor Marton
54978431e8SGabor Marton // Recursively descends into symbolic expressions and replaces symbols
55bc2c759aSGabor Marton // with their known values (in the sense of the getConstValue() method).
56978431e8SGabor Marton // We traverse the symbol tree and query the constraint values for the
57978431e8SGabor Marton // sub-trees and if a value is a constant we do the constant folding.
58978431e8SGabor Marton SVal simplifySValOnce(ProgramStateRef State, SVal V);
59978431e8SGabor Marton
60fa0734ecSArgyrios Kyrtzidis public:
SimpleSValBuilder(llvm::BumpPtrAllocator & alloc,ASTContext & context,ProgramStateManager & stateMgr)61fa0734ecSArgyrios Kyrtzidis SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
62001fd5b4STed Kremenek ProgramStateManager &stateMgr)
63fa0734ecSArgyrios Kyrtzidis : SValBuilder(alloc, context, stateMgr) {}
~SimpleSValBuilder()64637d1e66SAngel Garcia Gomez ~SimpleSValBuilder() override {}
65fa0734ecSArgyrios Kyrtzidis
66fb6b25b5SCraig Topper SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
67fb6b25b5SCraig Topper NonLoc lhs, NonLoc rhs, QualType resultTy) override;
68fb6b25b5SCraig Topper SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
69fb6b25b5SCraig Topper Loc lhs, Loc rhs, QualType resultTy) override;
70fb6b25b5SCraig Topper SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
71fb6b25b5SCraig Topper Loc lhs, NonLoc rhs, QualType resultTy) override;
72fa0734ecSArgyrios Kyrtzidis
73bc2c759aSGabor Marton /// Evaluates a given SVal by recursively evaluating and
74bc2c759aSGabor Marton /// simplifying the children SVals. If the SVal has only one possible
75fa0734ecSArgyrios Kyrtzidis /// (integer) value, that value is returned. Otherwise, returns NULL.
76fb6b25b5SCraig Topper const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override;
77fa0734ecSArgyrios Kyrtzidis
7812294f8dSArtem Dergachev SVal simplifySVal(ProgramStateRef State, SVal V) override;
7912294f8dSArtem Dergachev
80fa0734ecSArgyrios Kyrtzidis SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
81fa0734ecSArgyrios Kyrtzidis const llvm::APSInt &RHS, QualType resultTy);
82fa0734ecSArgyrios Kyrtzidis };
83fa0734ecSArgyrios Kyrtzidis } // end anonymous namespace
84fa0734ecSArgyrios Kyrtzidis
createSimpleSValBuilder(llvm::BumpPtrAllocator & alloc,ASTContext & context,ProgramStateManager & stateMgr)85fa0734ecSArgyrios Kyrtzidis SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
86fa0734ecSArgyrios Kyrtzidis ASTContext &context,
87001fd5b4STed Kremenek ProgramStateManager &stateMgr) {
88fa0734ecSArgyrios Kyrtzidis return new SimpleSValBuilder(alloc, context, stateMgr);
89fa0734ecSArgyrios Kyrtzidis }
90fa0734ecSArgyrios Kyrtzidis
9114742443STomasz Kamiński // Checks if the negation the value and flipping sign preserve
9214742443STomasz Kamiński // the semantics on the operation in the resultType
isNegationValuePreserving(const llvm::APSInt & Value,APSIntType ResultType)9314742443STomasz Kamiński static bool isNegationValuePreserving(const llvm::APSInt &Value,
9414742443STomasz Kamiński APSIntType ResultType) {
9514742443STomasz Kamiński const unsigned ValueBits = Value.getSignificantBits();
9614742443STomasz Kamiński if (ValueBits == ResultType.getBitWidth()) {
9714742443STomasz Kamiński // The value is the lowest negative value that is representable
9814742443STomasz Kamiński // in signed integer with bitWith of result type. The
9914742443STomasz Kamiński // negation is representable if resultType is unsigned.
10014742443STomasz Kamiński return ResultType.isUnsigned();
10114742443STomasz Kamiński }
10214742443STomasz Kamiński
10314742443STomasz Kamiński // If resultType bitWith is higher that number of bits required
10414742443STomasz Kamiński // to represent RHS, the sign flip produce same value.
10514742443STomasz Kamiński return ValueBits < ResultType.getBitWidth();
10614742443STomasz Kamiński }
10714742443STomasz Kamiński
108fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
109fa0734ecSArgyrios Kyrtzidis // Transfer function for binary operators.
110fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
111fa0734ecSArgyrios Kyrtzidis
MakeSymIntVal(const SymExpr * LHS,BinaryOperator::Opcode op,const llvm::APSInt & RHS,QualType resultTy)112fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
113fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode op,
114fa0734ecSArgyrios Kyrtzidis const llvm::APSInt &RHS,
115fa0734ecSArgyrios Kyrtzidis QualType resultTy) {
116fa0734ecSArgyrios Kyrtzidis bool isIdempotent = false;
117fa0734ecSArgyrios Kyrtzidis
118fa0734ecSArgyrios Kyrtzidis // Check for a few special cases with known reductions first.
119fa0734ecSArgyrios Kyrtzidis switch (op) {
120fa0734ecSArgyrios Kyrtzidis default:
121fa0734ecSArgyrios Kyrtzidis // We can't reduce this case; just treat it normally.
122fa0734ecSArgyrios Kyrtzidis break;
123fa0734ecSArgyrios Kyrtzidis case BO_Mul:
124fa0734ecSArgyrios Kyrtzidis // a*0 and a*1
125fa0734ecSArgyrios Kyrtzidis if (RHS == 0)
126fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy);
127fa0734ecSArgyrios Kyrtzidis else if (RHS == 1)
128fa0734ecSArgyrios Kyrtzidis isIdempotent = true;
129fa0734ecSArgyrios Kyrtzidis break;
130fa0734ecSArgyrios Kyrtzidis case BO_Div:
131fa0734ecSArgyrios Kyrtzidis // a/0 and a/1
132fa0734ecSArgyrios Kyrtzidis if (RHS == 0)
133fa0734ecSArgyrios Kyrtzidis // This is also handled elsewhere.
134fa0734ecSArgyrios Kyrtzidis return UndefinedVal();
135fa0734ecSArgyrios Kyrtzidis else if (RHS == 1)
136fa0734ecSArgyrios Kyrtzidis isIdempotent = true;
137fa0734ecSArgyrios Kyrtzidis break;
138fa0734ecSArgyrios Kyrtzidis case BO_Rem:
139fa0734ecSArgyrios Kyrtzidis // a%0 and a%1
140fa0734ecSArgyrios Kyrtzidis if (RHS == 0)
141fa0734ecSArgyrios Kyrtzidis // This is also handled elsewhere.
142fa0734ecSArgyrios Kyrtzidis return UndefinedVal();
143fa0734ecSArgyrios Kyrtzidis else if (RHS == 1)
144fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy);
145fa0734ecSArgyrios Kyrtzidis break;
146fa0734ecSArgyrios Kyrtzidis case BO_Add:
147fa0734ecSArgyrios Kyrtzidis case BO_Sub:
148fa0734ecSArgyrios Kyrtzidis case BO_Shl:
149fa0734ecSArgyrios Kyrtzidis case BO_Shr:
150fa0734ecSArgyrios Kyrtzidis case BO_Xor:
151fa0734ecSArgyrios Kyrtzidis // a+0, a-0, a<<0, a>>0, a^0
152fa0734ecSArgyrios Kyrtzidis if (RHS == 0)
153fa0734ecSArgyrios Kyrtzidis isIdempotent = true;
154fa0734ecSArgyrios Kyrtzidis break;
155fa0734ecSArgyrios Kyrtzidis case BO_And:
156fa0734ecSArgyrios Kyrtzidis // a&0 and a&(~0)
157fa0734ecSArgyrios Kyrtzidis if (RHS == 0)
158fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy);
159d933adeaSJay Foad else if (RHS.isAllOnes())
160fa0734ecSArgyrios Kyrtzidis isIdempotent = true;
161fa0734ecSArgyrios Kyrtzidis break;
162fa0734ecSArgyrios Kyrtzidis case BO_Or:
163fa0734ecSArgyrios Kyrtzidis // a|0 and a|(~0)
164fa0734ecSArgyrios Kyrtzidis if (RHS == 0)
165fa0734ecSArgyrios Kyrtzidis isIdempotent = true;
166d933adeaSJay Foad else if (RHS.isAllOnes()) {
167fa0734ecSArgyrios Kyrtzidis const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
168fa0734ecSArgyrios Kyrtzidis return nonloc::ConcreteInt(Result);
169fa0734ecSArgyrios Kyrtzidis }
170fa0734ecSArgyrios Kyrtzidis break;
171fa0734ecSArgyrios Kyrtzidis }
172fa0734ecSArgyrios Kyrtzidis
173fa0734ecSArgyrios Kyrtzidis // Idempotent ops (like a*1) can still change the type of an expression.
17401ddfa95SDenys Petrov // Wrap the LHS up in a NonLoc again and let evalCast do the
1755ad574c0SZhanyong Wan // dirty work.
176d066f79cSAnna Zaks if (isIdempotent)
17701ddfa95SDenys Petrov return evalCast(nonloc::SymbolVal(LHS), resultTy, QualType{});
178fa0734ecSArgyrios Kyrtzidis
179fa0734ecSArgyrios Kyrtzidis // If we reach this point, the expression cannot be simplified.
18054569448SJordy Rose // Make a SymbolVal for the entire expression, after converting the RHS.
18154569448SJordy Rose const llvm::APSInt *ConvertedRHS = &RHS;
18254569448SJordy Rose if (BinaryOperator::isComparisonOp(op)) {
18354569448SJordy Rose // We're looking for a type big enough to compare the symbolic value
18454569448SJordy Rose // with the given constant.
18554569448SJordy Rose // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
18654569448SJordy Rose ASTContext &Ctx = getContext();
187a808e165STed Kremenek QualType SymbolType = LHS->getType();
18854569448SJordy Rose uint64_t ValWidth = RHS.getBitWidth();
18954569448SJordy Rose uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
19054569448SJordy Rose
19154569448SJordy Rose if (ValWidth < TypeWidth) {
19254569448SJordy Rose // If the value is too small, extend it.
19354569448SJordy Rose ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
19454569448SJordy Rose } else if (ValWidth == TypeWidth) {
19554569448SJordy Rose // If the value is signed but the symbol is unsigned, do the comparison
19654569448SJordy Rose // in unsigned space. [C99 6.3.1.8]
19754569448SJordy Rose // (For the opposite case, the value is already unsigned.)
19854569448SJordy Rose if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
19954569448SJordy Rose ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
20054569448SJordy Rose }
20114742443STomasz Kamiński } else if (BinaryOperator::isAdditiveOp(op) && RHS.isNegative()) {
20214742443STomasz Kamiński // Change a+(-N) into a-N, and a-(-N) into a+N
20314742443STomasz Kamiński // Adjust addition/subtraction of negative value, to
20414742443STomasz Kamiński // subtraction/addition of the negated value.
20514742443STomasz Kamiński APSIntType resultIntTy = BasicVals.getAPSIntType(resultTy);
20614742443STomasz Kamiński if (isNegationValuePreserving(RHS, resultIntTy)) {
20714742443STomasz Kamiński ConvertedRHS = &BasicVals.getValue(-resultIntTy.convert(RHS));
20814742443STomasz Kamiński op = (op == BO_Add) ? BO_Sub : BO_Add;
20914742443STomasz Kamiński } else {
21014742443STomasz Kamiński ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
21114742443STomasz Kamiński }
212da5b5ae8SBalazs Benics } else
21354569448SJordy Rose ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
21454569448SJordy Rose
21554569448SJordy Rose return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
216fa0734ecSArgyrios Kyrtzidis }
217fa0734ecSArgyrios Kyrtzidis
2182bbccca9SAdam Balogh // See if Sym is known to be a relation Rel with Bound.
isInRelation(BinaryOperator::Opcode Rel,SymbolRef Sym,llvm::APSInt Bound,ProgramStateRef State)2192bbccca9SAdam Balogh static bool isInRelation(BinaryOperator::Opcode Rel, SymbolRef Sym,
2202bbccca9SAdam Balogh llvm::APSInt Bound, ProgramStateRef State) {
2212bbccca9SAdam Balogh SValBuilder &SVB = State->getStateManager().getSValBuilder();
2222bbccca9SAdam Balogh SVal Result =
2232bbccca9SAdam Balogh SVB.evalBinOpNN(State, Rel, nonloc::SymbolVal(Sym),
2242bbccca9SAdam Balogh nonloc::ConcreteInt(Bound), SVB.getConditionType());
2252bbccca9SAdam Balogh if (auto DV = Result.getAs<DefinedSVal>()) {
2262bbccca9SAdam Balogh return !State->assume(*DV, false);
2272bbccca9SAdam Balogh }
2282bbccca9SAdam Balogh return false;
2292bbccca9SAdam Balogh }
2302bbccca9SAdam Balogh
2312bbccca9SAdam Balogh // See if Sym is known to be within [min/4, max/4], where min and max
2322bbccca9SAdam Balogh // are the bounds of the symbol's integral type. With such symbols,
2332bbccca9SAdam Balogh // some manipulations can be performed without the risk of overflow.
2342bbccca9SAdam Balogh // assume() doesn't cause infinite recursion because we should be dealing
2352bbccca9SAdam Balogh // with simpler symbols on every recursive call.
isWithinConstantOverflowBounds(SymbolRef Sym,ProgramStateRef State)2362bbccca9SAdam Balogh static bool isWithinConstantOverflowBounds(SymbolRef Sym,
2372bbccca9SAdam Balogh ProgramStateRef State) {
2382bbccca9SAdam Balogh SValBuilder &SVB = State->getStateManager().getSValBuilder();
2392bbccca9SAdam Balogh BasicValueFactory &BV = SVB.getBasicValueFactory();
2402bbccca9SAdam Balogh
2412bbccca9SAdam Balogh QualType T = Sym->getType();
2422bbccca9SAdam Balogh assert(T->isSignedIntegerOrEnumerationType() &&
2432bbccca9SAdam Balogh "This only works with signed integers!");
2442bbccca9SAdam Balogh APSIntType AT = BV.getAPSIntType(T);
2452bbccca9SAdam Balogh
2462bbccca9SAdam Balogh llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
2472bbccca9SAdam Balogh return isInRelation(BO_LE, Sym, Max, State) &&
2482bbccca9SAdam Balogh isInRelation(BO_GE, Sym, Min, State);
2492bbccca9SAdam Balogh }
2502bbccca9SAdam Balogh
2512bbccca9SAdam Balogh // Same for the concrete integers: see if I is within [min/4, max/4].
isWithinConstantOverflowBounds(llvm::APSInt I)2522bbccca9SAdam Balogh static bool isWithinConstantOverflowBounds(llvm::APSInt I) {
2532bbccca9SAdam Balogh APSIntType AT(I);
2542bbccca9SAdam Balogh assert(!AT.isUnsigned() &&
2552bbccca9SAdam Balogh "This only works with signed integers!");
2562bbccca9SAdam Balogh
2572bbccca9SAdam Balogh llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
2582bbccca9SAdam Balogh return (I <= Max) && (I >= -Max);
2592bbccca9SAdam Balogh }
2602bbccca9SAdam Balogh
2612bbccca9SAdam Balogh static std::pair<SymbolRef, llvm::APSInt>
decomposeSymbol(SymbolRef Sym,BasicValueFactory & BV)2622bbccca9SAdam Balogh decomposeSymbol(SymbolRef Sym, BasicValueFactory &BV) {
2632bbccca9SAdam Balogh if (const auto *SymInt = dyn_cast<SymIntExpr>(Sym))
2642bbccca9SAdam Balogh if (BinaryOperator::isAdditiveOp(SymInt->getOpcode()))
2652bbccca9SAdam Balogh return std::make_pair(SymInt->getLHS(),
2662bbccca9SAdam Balogh (SymInt->getOpcode() == BO_Add) ?
2672bbccca9SAdam Balogh (SymInt->getRHS()) :
2682bbccca9SAdam Balogh (-SymInt->getRHS()));
2692bbccca9SAdam Balogh
2702bbccca9SAdam Balogh // Fail to decompose: "reduce" the problem to the "$x + 0" case.
2712bbccca9SAdam Balogh return std::make_pair(Sym, BV.getValue(0, Sym->getType()));
2722bbccca9SAdam Balogh }
2732bbccca9SAdam Balogh
2742bbccca9SAdam Balogh // Simplify "(LSym + LInt) Op (RSym + RInt)" assuming all values are of the
2752bbccca9SAdam Balogh // same signed integral type and no overflows occur (which should be checked
2762bbccca9SAdam Balogh // by the caller).
doRearrangeUnchecked(ProgramStateRef State,BinaryOperator::Opcode Op,SymbolRef LSym,llvm::APSInt LInt,SymbolRef RSym,llvm::APSInt RInt)2772bbccca9SAdam Balogh static NonLoc doRearrangeUnchecked(ProgramStateRef State,
2782bbccca9SAdam Balogh BinaryOperator::Opcode Op,
2792bbccca9SAdam Balogh SymbolRef LSym, llvm::APSInt LInt,
2802bbccca9SAdam Balogh SymbolRef RSym, llvm::APSInt RInt) {
2812bbccca9SAdam Balogh SValBuilder &SVB = State->getStateManager().getSValBuilder();
2822bbccca9SAdam Balogh BasicValueFactory &BV = SVB.getBasicValueFactory();
2832bbccca9SAdam Balogh SymbolManager &SymMgr = SVB.getSymbolManager();
2842bbccca9SAdam Balogh
2852bbccca9SAdam Balogh QualType SymTy = LSym->getType();
2862bbccca9SAdam Balogh assert(SymTy == RSym->getType() &&
2872bbccca9SAdam Balogh "Symbols are not of the same type!");
2882bbccca9SAdam Balogh assert(APSIntType(LInt) == BV.getAPSIntType(SymTy) &&
2892bbccca9SAdam Balogh "Integers are not of the same type as symbols!");
2902bbccca9SAdam Balogh assert(APSIntType(RInt) == BV.getAPSIntType(SymTy) &&
2912bbccca9SAdam Balogh "Integers are not of the same type as symbols!");
2922bbccca9SAdam Balogh
2932bbccca9SAdam Balogh QualType ResultTy;
2942bbccca9SAdam Balogh if (BinaryOperator::isComparisonOp(Op))
2952bbccca9SAdam Balogh ResultTy = SVB.getConditionType();
2962bbccca9SAdam Balogh else if (BinaryOperator::isAdditiveOp(Op))
2972bbccca9SAdam Balogh ResultTy = SymTy;
2982bbccca9SAdam Balogh else
2992bbccca9SAdam Balogh llvm_unreachable("Operation not suitable for unchecked rearrangement!");
3002bbccca9SAdam Balogh
3012bbccca9SAdam Balogh if (LSym == RSym)
3022bbccca9SAdam Balogh return SVB.evalBinOpNN(State, Op, nonloc::ConcreteInt(LInt),
3032bbccca9SAdam Balogh nonloc::ConcreteInt(RInt), ResultTy)
3042bbccca9SAdam Balogh .castAs<NonLoc>();
3052bbccca9SAdam Balogh
3062bbccca9SAdam Balogh SymbolRef ResultSym = nullptr;
3072bbccca9SAdam Balogh BinaryOperator::Opcode ResultOp;
3082bbccca9SAdam Balogh llvm::APSInt ResultInt;
3092bbccca9SAdam Balogh if (BinaryOperator::isComparisonOp(Op)) {
3102bbccca9SAdam Balogh // Prefer comparing to a non-negative number.
3112bbccca9SAdam Balogh // FIXME: Maybe it'd be better to have consistency in
3122bbccca9SAdam Balogh // "$x - $y" vs. "$y - $x" because those are solver's keys.
3132bbccca9SAdam Balogh if (LInt > RInt) {
3142bbccca9SAdam Balogh ResultSym = SymMgr.getSymSymExpr(RSym, BO_Sub, LSym, SymTy);
3152bbccca9SAdam Balogh ResultOp = BinaryOperator::reverseComparisonOp(Op);
3162bbccca9SAdam Balogh ResultInt = LInt - RInt; // Opposite order!
3172bbccca9SAdam Balogh } else {
3182bbccca9SAdam Balogh ResultSym = SymMgr.getSymSymExpr(LSym, BO_Sub, RSym, SymTy);
3192bbccca9SAdam Balogh ResultOp = Op;
3202bbccca9SAdam Balogh ResultInt = RInt - LInt; // Opposite order!
3212bbccca9SAdam Balogh }
3222bbccca9SAdam Balogh } else {
3232bbccca9SAdam Balogh ResultSym = SymMgr.getSymSymExpr(LSym, Op, RSym, SymTy);
3242bbccca9SAdam Balogh ResultInt = (Op == BO_Add) ? (LInt + RInt) : (LInt - RInt);
3252bbccca9SAdam Balogh ResultOp = BO_Add;
3262bbccca9SAdam Balogh // Bring back the cosmetic difference.
3272bbccca9SAdam Balogh if (ResultInt < 0) {
3282bbccca9SAdam Balogh ResultInt = -ResultInt;
3292bbccca9SAdam Balogh ResultOp = BO_Sub;
3302bbccca9SAdam Balogh } else if (ResultInt == 0) {
3312bbccca9SAdam Balogh // Shortcut: Simplify "$x + 0" to "$x".
3322bbccca9SAdam Balogh return nonloc::SymbolVal(ResultSym);
3332bbccca9SAdam Balogh }
3342bbccca9SAdam Balogh }
3352bbccca9SAdam Balogh const llvm::APSInt &PersistentResultInt = BV.getValue(ResultInt);
3362bbccca9SAdam Balogh return nonloc::SymbolVal(
3372bbccca9SAdam Balogh SymMgr.getSymIntExpr(ResultSym, ResultOp, PersistentResultInt, ResultTy));
3382bbccca9SAdam Balogh }
3392bbccca9SAdam Balogh
3402bbccca9SAdam Balogh // Rearrange if symbol type matches the result type and if the operator is a
3412bbccca9SAdam Balogh // comparison operator, both symbol and constant must be within constant
3422bbccca9SAdam Balogh // overflow bounds.
shouldRearrange(ProgramStateRef State,BinaryOperator::Opcode Op,SymbolRef Sym,llvm::APSInt Int,QualType Ty)3432bbccca9SAdam Balogh static bool shouldRearrange(ProgramStateRef State, BinaryOperator::Opcode Op,
3442bbccca9SAdam Balogh SymbolRef Sym, llvm::APSInt Int, QualType Ty) {
3452bbccca9SAdam Balogh return Sym->getType() == Ty &&
3462bbccca9SAdam Balogh (!BinaryOperator::isComparisonOp(Op) ||
3472bbccca9SAdam Balogh (isWithinConstantOverflowBounds(Sym, State) &&
3482bbccca9SAdam Balogh isWithinConstantOverflowBounds(Int)));
3492bbccca9SAdam Balogh }
3502bbccca9SAdam Balogh
tryRearrange(ProgramStateRef State,BinaryOperator::Opcode Op,NonLoc Lhs,NonLoc Rhs,QualType ResultTy)3512bbccca9SAdam Balogh static Optional<NonLoc> tryRearrange(ProgramStateRef State,
3522bbccca9SAdam Balogh BinaryOperator::Opcode Op, NonLoc Lhs,
3532bbccca9SAdam Balogh NonLoc Rhs, QualType ResultTy) {
3542bbccca9SAdam Balogh ProgramStateManager &StateMgr = State->getStateManager();
3552bbccca9SAdam Balogh SValBuilder &SVB = StateMgr.getSValBuilder();
3562bbccca9SAdam Balogh
3572bbccca9SAdam Balogh // We expect everything to be of the same type - this type.
3582bbccca9SAdam Balogh QualType SingleTy;
3592bbccca9SAdam Balogh
360dcde8accSAdam Balogh // FIXME: After putting complexity threshold to the symbols we can always
361dcde8accSAdam Balogh // rearrange additive operations but rearrange comparisons only if
362dcde8accSAdam Balogh // option is set.
363b97a9640SBalazs Benics if (!SVB.getAnalyzerOptions().ShouldAggressivelySimplifyBinaryOperation)
364dcde8accSAdam Balogh return None;
365dcde8accSAdam Balogh
3662bbccca9SAdam Balogh SymbolRef LSym = Lhs.getAsSymbol();
3672bbccca9SAdam Balogh if (!LSym)
3682bbccca9SAdam Balogh return None;
3692bbccca9SAdam Balogh
370dcde8accSAdam Balogh if (BinaryOperator::isComparisonOp(Op)) {
3712bbccca9SAdam Balogh SingleTy = LSym->getType();
3722bbccca9SAdam Balogh if (ResultTy != SVB.getConditionType())
3732bbccca9SAdam Balogh return None;
3742bbccca9SAdam Balogh // Initialize SingleTy later with a symbol's type.
3752bbccca9SAdam Balogh } else if (BinaryOperator::isAdditiveOp(Op)) {
3762bbccca9SAdam Balogh SingleTy = ResultTy;
37713e186c0SAdam Balogh if (LSym->getType() != SingleTy)
37813e186c0SAdam Balogh return None;
3792bbccca9SAdam Balogh } else {
3802bbccca9SAdam Balogh // Don't rearrange other operations.
3812bbccca9SAdam Balogh return None;
3822bbccca9SAdam Balogh }
3832bbccca9SAdam Balogh
3842bbccca9SAdam Balogh assert(!SingleTy.isNull() && "We should have figured out the type by now!");
3852bbccca9SAdam Balogh
386471d0864SAdam Balogh // Rearrange signed symbolic expressions only
387471d0864SAdam Balogh if (!SingleTy->isSignedIntegerOrEnumerationType())
388471d0864SAdam Balogh return None;
389471d0864SAdam Balogh
3902bbccca9SAdam Balogh SymbolRef RSym = Rhs.getAsSymbol();
3912bbccca9SAdam Balogh if (!RSym || RSym->getType() != SingleTy)
3922bbccca9SAdam Balogh return None;
3932bbccca9SAdam Balogh
3942bbccca9SAdam Balogh BasicValueFactory &BV = State->getBasicVals();
3952bbccca9SAdam Balogh llvm::APSInt LInt, RInt;
3962bbccca9SAdam Balogh std::tie(LSym, LInt) = decomposeSymbol(LSym, BV);
3972bbccca9SAdam Balogh std::tie(RSym, RInt) = decomposeSymbol(RSym, BV);
3982bbccca9SAdam Balogh if (!shouldRearrange(State, Op, LSym, LInt, SingleTy) ||
3992bbccca9SAdam Balogh !shouldRearrange(State, Op, RSym, RInt, SingleTy))
4002bbccca9SAdam Balogh return None;
4012bbccca9SAdam Balogh
4022bbccca9SAdam Balogh // We know that no overflows can occur anymore.
4032bbccca9SAdam Balogh return doRearrangeUnchecked(State, Op, LSym, LInt, RSym, RInt);
4042bbccca9SAdam Balogh }
4052bbccca9SAdam Balogh
evalBinOpNN(ProgramStateRef state,BinaryOperator::Opcode op,NonLoc lhs,NonLoc rhs,QualType resultTy)40649b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
407fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode op,
408fa0734ecSArgyrios Kyrtzidis NonLoc lhs, NonLoc rhs,
409fa0734ecSArgyrios Kyrtzidis QualType resultTy) {
410f0e9ca86SAnna Zaks NonLoc InputLHS = lhs;
411f0e9ca86SAnna Zaks NonLoc InputRHS = rhs;
412f0e9ca86SAnna Zaks
41312887a20SGabor Marton // Constraints may have changed since the creation of a bound SVal. Check if
41412887a20SGabor Marton // the values can be simplified based on those new constraints.
41512887a20SGabor Marton SVal simplifiedLhs = simplifySVal(state, lhs);
41612887a20SGabor Marton SVal simplifiedRhs = simplifySVal(state, rhs);
41712887a20SGabor Marton if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>())
41812887a20SGabor Marton lhs = *simplifiedLhsAsNonLoc;
41912887a20SGabor Marton if (auto simplifiedRhsAsNonLoc = simplifiedRhs.getAs<NonLoc>())
42012887a20SGabor Marton rhs = *simplifiedRhsAsNonLoc;
42112887a20SGabor Marton
422fa0734ecSArgyrios Kyrtzidis // Handle trivial case where left-side and right-side are the same.
423fa0734ecSArgyrios Kyrtzidis if (lhs == rhs)
424fa0734ecSArgyrios Kyrtzidis switch (op) {
425fa0734ecSArgyrios Kyrtzidis default:
426fa0734ecSArgyrios Kyrtzidis break;
427fa0734ecSArgyrios Kyrtzidis case BO_EQ:
428fa0734ecSArgyrios Kyrtzidis case BO_LE:
429fa0734ecSArgyrios Kyrtzidis case BO_GE:
430fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy);
431fa0734ecSArgyrios Kyrtzidis case BO_LT:
432fa0734ecSArgyrios Kyrtzidis case BO_GT:
433fa0734ecSArgyrios Kyrtzidis case BO_NE:
434fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy);
435fa0734ecSArgyrios Kyrtzidis case BO_Xor:
436fa0734ecSArgyrios Kyrtzidis case BO_Sub:
4377523d1a8SJordan Rose if (resultTy->isIntegralOrEnumerationType())
438fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy);
43901ddfa95SDenys Petrov return evalCast(makeIntVal(0, /*isUnsigned=*/false), resultTy,
44001ddfa95SDenys Petrov QualType{});
441fa0734ecSArgyrios Kyrtzidis case BO_Or:
442fa0734ecSArgyrios Kyrtzidis case BO_And:
44301ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{});
444fa0734ecSArgyrios Kyrtzidis }
445fa0734ecSArgyrios Kyrtzidis
44640446663SKazu Hirata while (true) {
447fa0734ecSArgyrios Kyrtzidis switch (lhs.getSubKind()) {
448fa0734ecSArgyrios Kyrtzidis default:
449bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, lhs, rhs, resultTy);
45064c01f7bSDevin Coughlin case nonloc::PointerToMemberKind: {
45164c01f7bSDevin Coughlin assert(rhs.getSubKind() == nonloc::PointerToMemberKind &&
45264c01f7bSDevin Coughlin "Both SVals should have pointer-to-member-type");
45364c01f7bSDevin Coughlin auto LPTM = lhs.castAs<nonloc::PointerToMember>(),
45464c01f7bSDevin Coughlin RPTM = rhs.castAs<nonloc::PointerToMember>();
45564c01f7bSDevin Coughlin auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData();
45664c01f7bSDevin Coughlin switch (op) {
45764c01f7bSDevin Coughlin case BO_EQ:
45864c01f7bSDevin Coughlin return makeTruthVal(LPTMD == RPTMD, resultTy);
45964c01f7bSDevin Coughlin case BO_NE:
46064c01f7bSDevin Coughlin return makeTruthVal(LPTMD != RPTMD, resultTy);
46164c01f7bSDevin Coughlin default:
46264c01f7bSDevin Coughlin return UnknownVal();
46364c01f7bSDevin Coughlin }
46464c01f7bSDevin Coughlin }
465fa0734ecSArgyrios Kyrtzidis case nonloc::LocAsIntegerKind: {
4662fdacbc5SDavid Blaikie Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc();
467fa0734ecSArgyrios Kyrtzidis switch (rhs.getSubKind()) {
468fa0734ecSArgyrios Kyrtzidis case nonloc::LocAsIntegerKind:
46918d77984SAlexander Shaposhnikov // FIXME: at the moment the implementation
47018d77984SAlexander Shaposhnikov // of modeling "pointers as integers" is not complete.
47118d77984SAlexander Shaposhnikov if (!BinaryOperator::isComparisonOp(op))
47218d77984SAlexander Shaposhnikov return UnknownVal();
473fa0734ecSArgyrios Kyrtzidis return evalBinOpLL(state, op, lhsL,
4742fdacbc5SDavid Blaikie rhs.castAs<nonloc::LocAsInteger>().getLoc(),
475fa0734ecSArgyrios Kyrtzidis resultTy);
476fa0734ecSArgyrios Kyrtzidis case nonloc::ConcreteIntKind: {
47718d77984SAlexander Shaposhnikov // FIXME: at the moment the implementation
47818d77984SAlexander Shaposhnikov // of modeling "pointers as integers" is not complete.
47918d77984SAlexander Shaposhnikov if (!BinaryOperator::isComparisonOp(op))
48018d77984SAlexander Shaposhnikov return UnknownVal();
481fa0734ecSArgyrios Kyrtzidis // Transform the integer into a location and compare.
4827333a9eaSArtem Dergachev // FIXME: This only makes sense for comparisons. If we want to, say,
4837333a9eaSArtem Dergachev // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it,
4847333a9eaSArtem Dergachev // then pack it back into a LocAsInteger.
4852fdacbc5SDavid Blaikie llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue();
48627ed855aSDavid Stenberg // If the region has a symbolic base, pay attention to the type; it
48727ed855aSDavid Stenberg // might be coming from a non-default address space. For non-symbolic
48827ed855aSDavid Stenberg // regions it doesn't matter that much because such comparisons would
48927ed855aSDavid Stenberg // most likely evaluate to concrete false anyway. FIXME: We might
49027ed855aSDavid Stenberg // still need to handle the non-comparison case.
49127ed855aSDavid Stenberg if (SymbolRef lSym = lhs.getAsLocSymbol(true))
49227ed855aSDavid Stenberg BasicVals.getAPSIntType(lSym->getType()).apply(i);
49327ed855aSDavid Stenberg else
4947e3c3ea3SJordy Rose BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
495fa0734ecSArgyrios Kyrtzidis return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
496fa0734ecSArgyrios Kyrtzidis }
497fa0734ecSArgyrios Kyrtzidis default:
498fa0734ecSArgyrios Kyrtzidis switch (op) {
499fa0734ecSArgyrios Kyrtzidis case BO_EQ:
500fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy);
501fa0734ecSArgyrios Kyrtzidis case BO_NE:
502fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy);
503fa0734ecSArgyrios Kyrtzidis default:
504fa0734ecSArgyrios Kyrtzidis // This case also handles pointer arithmetic.
505bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
506fa0734ecSArgyrios Kyrtzidis }
507fa0734ecSArgyrios Kyrtzidis }
508fa0734ecSArgyrios Kyrtzidis }
509d066f79cSAnna Zaks case nonloc::ConcreteIntKind: {
5102fdacbc5SDavid Blaikie llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
511d066f79cSAnna Zaks
51254569448SJordy Rose // If we're dealing with two known constants, just perform the operation.
513bc2c759aSGabor Marton if (const llvm::APSInt *KnownRHSValue = getConstValue(state, rhs)) {
51454569448SJordy Rose llvm::APSInt RHSValue = *KnownRHSValue;
51554569448SJordy Rose if (BinaryOperator::isComparisonOp(op)) {
51654569448SJordy Rose // We're looking for a type big enough to compare the two values.
5177e3c3ea3SJordy Rose // FIXME: This is not correct. char + short will result in a promotion
5187e3c3ea3SJordy Rose // to int. Unfortunately we have lost types by this point.
5197e3c3ea3SJordy Rose APSIntType CompareType = std::max(APSIntType(LHSValue),
5207e3c3ea3SJordy Rose APSIntType(RHSValue));
5217e3c3ea3SJordy Rose CompareType.apply(LHSValue);
5227e3c3ea3SJordy Rose CompareType.apply(RHSValue);
52354569448SJordy Rose } else if (!BinaryOperator::isShiftOp(op)) {
5247e3c3ea3SJordy Rose APSIntType IntType = BasicVals.getAPSIntType(resultTy);
5257e3c3ea3SJordy Rose IntType.apply(LHSValue);
5267e3c3ea3SJordy Rose IntType.apply(RHSValue);
527d066f79cSAnna Zaks }
528d066f79cSAnna Zaks
52954569448SJordy Rose const llvm::APSInt *Result =
53054569448SJordy Rose BasicVals.evalAPSInt(op, LHSValue, RHSValue);
53154569448SJordy Rose if (!Result)
53254569448SJordy Rose return UndefinedVal();
53354569448SJordy Rose
53454569448SJordy Rose return nonloc::ConcreteInt(*Result);
53554569448SJordy Rose }
536d066f79cSAnna Zaks
537d066f79cSAnna Zaks // Swap the left and right sides and flip the operator if doing so
538d066f79cSAnna Zaks // allows us to better reason about the expression (this is a form
539d066f79cSAnna Zaks // of expression canonicalization).
540d066f79cSAnna Zaks // While we're at it, catch some special cases for non-commutative ops.
541d066f79cSAnna Zaks switch (op) {
542d066f79cSAnna Zaks case BO_LT:
543d066f79cSAnna Zaks case BO_GT:
544d066f79cSAnna Zaks case BO_LE:
545d066f79cSAnna Zaks case BO_GE:
546604d0bbbSJordan Rose op = BinaryOperator::reverseComparisonOp(op);
5474dc0b1acSReid Kleckner LLVM_FALLTHROUGH;
548d066f79cSAnna Zaks case BO_EQ:
549d066f79cSAnna Zaks case BO_NE:
550d066f79cSAnna Zaks case BO_Add:
551d066f79cSAnna Zaks case BO_Mul:
552d066f79cSAnna Zaks case BO_And:
553d066f79cSAnna Zaks case BO_Xor:
554d066f79cSAnna Zaks case BO_Or:
55554569448SJordy Rose std::swap(lhs, rhs);
556d066f79cSAnna Zaks continue;
557d066f79cSAnna Zaks case BO_Shr:
55854569448SJordy Rose // (~0)>>a
559d933adeaSJay Foad if (LHSValue.isAllOnes() && LHSValue.isSigned())
56001ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{});
5614dc0b1acSReid Kleckner LLVM_FALLTHROUGH;
562d066f79cSAnna Zaks case BO_Shl:
56354569448SJordy Rose // 0<<a and 0>>a
56454569448SJordy Rose if (LHSValue == 0)
56501ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{});
566bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
567015c3988SGabor Marton case BO_Div:
568015c3988SGabor Marton // 0 / x == 0
56973c120a9SValeriy Savchenko case BO_Rem:
57073c120a9SValeriy Savchenko // 0 % x == 0
57173c120a9SValeriy Savchenko if (LHSValue == 0)
57273c120a9SValeriy Savchenko return makeZeroVal(resultTy);
57373c120a9SValeriy Savchenko LLVM_FALLTHROUGH;
574d066f79cSAnna Zaks default:
575bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
576d066f79cSAnna Zaks }
577d066f79cSAnna Zaks }
578d066f79cSAnna Zaks case nonloc::SymbolValKind: {
57954569448SJordy Rose // We only handle LHS as simple symbols or SymIntExprs.
5802fdacbc5SDavid Blaikie SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
581d066f79cSAnna Zaks
582d066f79cSAnna Zaks // LHS is a symbolic expression.
58354569448SJordy Rose if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
584fa0734ecSArgyrios Kyrtzidis
585fa0734ecSArgyrios Kyrtzidis // Is this a logical not? (!x is represented as x == 0.)
586fa0734ecSArgyrios Kyrtzidis if (op == BO_EQ && rhs.isZeroConstant()) {
587fa0734ecSArgyrios Kyrtzidis // We know how to negate certain expressions. Simplify them here.
588fa0734ecSArgyrios Kyrtzidis
589fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode opc = symIntExpr->getOpcode();
590fa0734ecSArgyrios Kyrtzidis switch (opc) {
591fa0734ecSArgyrios Kyrtzidis default:
592fa0734ecSArgyrios Kyrtzidis // We don't know how to negate this operation.
593fa0734ecSArgyrios Kyrtzidis // Just handle it as if it were a normal comparison to 0.
594fa0734ecSArgyrios Kyrtzidis break;
595fa0734ecSArgyrios Kyrtzidis case BO_LAnd:
596fa0734ecSArgyrios Kyrtzidis case BO_LOr:
59783d382b1SDavid Blaikie llvm_unreachable("Logical operators handled by branching logic.");
598fa0734ecSArgyrios Kyrtzidis case BO_Assign:
599fa0734ecSArgyrios Kyrtzidis case BO_MulAssign:
600fa0734ecSArgyrios Kyrtzidis case BO_DivAssign:
601fa0734ecSArgyrios Kyrtzidis case BO_RemAssign:
602fa0734ecSArgyrios Kyrtzidis case BO_AddAssign:
603fa0734ecSArgyrios Kyrtzidis case BO_SubAssign:
604fa0734ecSArgyrios Kyrtzidis case BO_ShlAssign:
605fa0734ecSArgyrios Kyrtzidis case BO_ShrAssign:
606fa0734ecSArgyrios Kyrtzidis case BO_AndAssign:
607fa0734ecSArgyrios Kyrtzidis case BO_XorAssign:
608fa0734ecSArgyrios Kyrtzidis case BO_OrAssign:
609fa0734ecSArgyrios Kyrtzidis case BO_Comma:
61083d382b1SDavid Blaikie llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
611fa0734ecSArgyrios Kyrtzidis case BO_PtrMemD:
612fa0734ecSArgyrios Kyrtzidis case BO_PtrMemI:
61383d382b1SDavid Blaikie llvm_unreachable("Pointer arithmetic not handled here.");
614fa0734ecSArgyrios Kyrtzidis case BO_LT:
615fa0734ecSArgyrios Kyrtzidis case BO_GT:
616fa0734ecSArgyrios Kyrtzidis case BO_LE:
617fa0734ecSArgyrios Kyrtzidis case BO_GE:
618fa0734ecSArgyrios Kyrtzidis case BO_EQ:
619fa0734ecSArgyrios Kyrtzidis case BO_NE:
620dc16628cSJordan Rose assert(resultTy->isBooleanType() ||
621dc16628cSJordan Rose resultTy == getConditionType());
622dc16628cSJordan Rose assert(symIntExpr->getType()->isBooleanType() ||
623dc16628cSJordan Rose getContext().hasSameUnqualifiedType(symIntExpr->getType(),
624dc16628cSJordan Rose getConditionType()));
625fa0734ecSArgyrios Kyrtzidis // Negate the comparison and make a value.
626604d0bbbSJordan Rose opc = BinaryOperator::negateComparisonOp(opc);
627fa0734ecSArgyrios Kyrtzidis return makeNonLoc(symIntExpr->getLHS(), opc,
628fa0734ecSArgyrios Kyrtzidis symIntExpr->getRHS(), resultTy);
629fa0734ecSArgyrios Kyrtzidis }
630fa0734ecSArgyrios Kyrtzidis }
631fa0734ecSArgyrios Kyrtzidis
632fa0734ecSArgyrios Kyrtzidis // For now, only handle expressions whose RHS is a constant.
633bc2c759aSGabor Marton if (const llvm::APSInt *RHSValue = getConstValue(state, rhs)) {
634fa0734ecSArgyrios Kyrtzidis // If both the LHS and the current expression are additive,
63554569448SJordy Rose // fold their constants and try again.
636fa0734ecSArgyrios Kyrtzidis if (BinaryOperator::isAdditiveOp(op)) {
637fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode lop = symIntExpr->getOpcode();
638fa0734ecSArgyrios Kyrtzidis if (BinaryOperator::isAdditiveOp(lop)) {
63954569448SJordy Rose // Convert the two constants to a common type, then combine them.
64054569448SJordy Rose
641fa0734ecSArgyrios Kyrtzidis // resultTy may not be the best type to convert to, but it's
642fa0734ecSArgyrios Kyrtzidis // probably the best choice in expressions with mixed type
643fa0734ecSArgyrios Kyrtzidis // (such as x+1U+2LL). The rules for implicit conversions should
644fa0734ecSArgyrios Kyrtzidis // choose a reasonable type to preserve the expression, and will
645fa0734ecSArgyrios Kyrtzidis // at least match how the value is going to be used.
6467e3c3ea3SJordy Rose APSIntType IntType = BasicVals.getAPSIntType(resultTy);
6477e3c3ea3SJordy Rose const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
6487e3c3ea3SJordy Rose const llvm::APSInt &second = IntType.convert(*RHSValue);
64954569448SJordy Rose
65014742443STomasz Kamiński // If the op and lop agrees, then we just need to
65114742443STomasz Kamiński // sum the constants. Otherwise, we change to operation
65214742443STomasz Kamiński // type if substraction would produce negative value
65314742443STomasz Kamiński // (and cause overflow for unsigned integers),
65414742443STomasz Kamiński // as consequence x+1U-10 produces x-9U, instead
65514742443STomasz Kamiński // of x+4294967287U, that would be produced without this
65614742443STomasz Kamiński // additional check.
657fa0734ecSArgyrios Kyrtzidis const llvm::APSInt *newRHS;
65814742443STomasz Kamiński if (lop == op) {
659fa0734ecSArgyrios Kyrtzidis newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
66014742443STomasz Kamiński } else if (first >= second) {
661fa0734ecSArgyrios Kyrtzidis newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
66214742443STomasz Kamiński op = lop;
66314742443STomasz Kamiński } else {
66414742443STomasz Kamiński newRHS = BasicVals.evalAPSInt(BO_Sub, second, first);
66514742443STomasz Kamiński }
66654569448SJordy Rose
66754569448SJordy Rose assert(newRHS && "Invalid operation despite common type!");
66854569448SJordy Rose rhs = nonloc::ConcreteInt(*newRHS);
66954569448SJordy Rose lhs = nonloc::SymbolVal(symIntExpr->getLHS());
67054569448SJordy Rose continue;
671fa0734ecSArgyrios Kyrtzidis }
672fa0734ecSArgyrios Kyrtzidis }
673fa0734ecSArgyrios Kyrtzidis
67454569448SJordy Rose // Otherwise, make a SymIntExpr out of the expression.
67554569448SJordy Rose return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
67654569448SJordy Rose }
6773b4c3ea2SJordan Rose }
678fa0734ecSArgyrios Kyrtzidis
67954569448SJordy Rose // Is the RHS a constant?
680bc2c759aSGabor Marton if (const llvm::APSInt *RHSValue = getConstValue(state, rhs))
68154569448SJordy Rose return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
682fa0734ecSArgyrios Kyrtzidis
6832bbccca9SAdam Balogh if (Optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy))
6842bbccca9SAdam Balogh return *V;
6852bbccca9SAdam Balogh
68654569448SJordy Rose // Give up -- this is not a symbolic expression we can handle.
687bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
688fa0734ecSArgyrios Kyrtzidis }
689fa0734ecSArgyrios Kyrtzidis }
690fa0734ecSArgyrios Kyrtzidis }
691fa0734ecSArgyrios Kyrtzidis }
692fa0734ecSArgyrios Kyrtzidis
evalBinOpFieldRegionFieldRegion(const FieldRegion * LeftFR,const FieldRegion * RightFR,BinaryOperator::Opcode op,QualType resultTy,SimpleSValBuilder & SVB)693bac964e1SAnna Zaks static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR,
694bac964e1SAnna Zaks const FieldRegion *RightFR,
695bac964e1SAnna Zaks BinaryOperator::Opcode op,
696bac964e1SAnna Zaks QualType resultTy,
697bac964e1SAnna Zaks SimpleSValBuilder &SVB) {
698bac964e1SAnna Zaks // Only comparisons are meaningful here!
699bac964e1SAnna Zaks if (!BinaryOperator::isComparisonOp(op))
700bac964e1SAnna Zaks return UnknownVal();
701bac964e1SAnna Zaks
702bac964e1SAnna Zaks // Next, see if the two FRs have the same super-region.
703bac964e1SAnna Zaks // FIXME: This doesn't handle casts yet, and simply stripping the casts
704bac964e1SAnna Zaks // doesn't help.
705bac964e1SAnna Zaks if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
706bac964e1SAnna Zaks return UnknownVal();
707bac964e1SAnna Zaks
708bac964e1SAnna Zaks const FieldDecl *LeftFD = LeftFR->getDecl();
709bac964e1SAnna Zaks const FieldDecl *RightFD = RightFR->getDecl();
710bac964e1SAnna Zaks const RecordDecl *RD = LeftFD->getParent();
711bac964e1SAnna Zaks
712bac964e1SAnna Zaks // Make sure the two FRs are from the same kind of record. Just in case!
713bac964e1SAnna Zaks // FIXME: This is probably where inheritance would be a problem.
714bac964e1SAnna Zaks if (RD != RightFD->getParent())
715bac964e1SAnna Zaks return UnknownVal();
716bac964e1SAnna Zaks
717bac964e1SAnna Zaks // We know for sure that the two fields are not the same, since that
718bac964e1SAnna Zaks // would have given us the same SVal.
719bac964e1SAnna Zaks if (op == BO_EQ)
720bac964e1SAnna Zaks return SVB.makeTruthVal(false, resultTy);
721bac964e1SAnna Zaks if (op == BO_NE)
722bac964e1SAnna Zaks return SVB.makeTruthVal(true, resultTy);
723bac964e1SAnna Zaks
724bac964e1SAnna Zaks // Iterate through the fields and see which one comes first.
725bac964e1SAnna Zaks // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
726bac964e1SAnna Zaks // members and the units in which bit-fields reside have addresses that
727bac964e1SAnna Zaks // increase in the order in which they are declared."
728bac964e1SAnna Zaks bool leftFirst = (op == BO_LT || op == BO_LE);
729e8a8baefSAaron Ballman for (const auto *I : RD->fields()) {
730e8a8baefSAaron Ballman if (I == LeftFD)
731bac964e1SAnna Zaks return SVB.makeTruthVal(leftFirst, resultTy);
732e8a8baefSAaron Ballman if (I == RightFD)
733bac964e1SAnna Zaks return SVB.makeTruthVal(!leftFirst, resultTy);
734bac964e1SAnna Zaks }
735bac964e1SAnna Zaks
736bac964e1SAnna Zaks llvm_unreachable("Fields not found in parent record's definition");
737bac964e1SAnna Zaks }
738bac964e1SAnna Zaks
7394d5b824eSVince Bridgers // This is used in debug builds only for now because some downstream users
7404d5b824eSVince Bridgers // may hit this assert in their subsequent merges.
7414d5b824eSVince Bridgers // There are still places in the analyzer where equal bitwidth Locs
7424d5b824eSVince Bridgers // are compared, and need to be found and corrected. Recent previous fixes have
7434d5b824eSVince Bridgers // addressed the known problems of making NULLs with specific bitwidths
7444d5b824eSVince Bridgers // for Loc comparisons along with deprecation of APIs for the same purpose.
7454d5b824eSVince Bridgers //
assertEqualBitWidths(ProgramStateRef State,Loc RhsLoc,Loc LhsLoc)7464d5b824eSVince Bridgers static void assertEqualBitWidths(ProgramStateRef State, Loc RhsLoc,
7474d5b824eSVince Bridgers Loc LhsLoc) {
7484d5b824eSVince Bridgers // Implements a "best effort" check for RhsLoc and LhsLoc bit widths
7494d5b824eSVince Bridgers ASTContext &Ctx = State->getStateManager().getContext();
7504d5b824eSVince Bridgers uint64_t RhsBitwidth =
7514d5b824eSVince Bridgers RhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(RhsLoc.getType(Ctx));
7524d5b824eSVince Bridgers uint64_t LhsBitwidth =
7534d5b824eSVince Bridgers LhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(LhsLoc.getType(Ctx));
7544d5b824eSVince Bridgers if (RhsBitwidth && LhsBitwidth &&
7554d5b824eSVince Bridgers (LhsLoc.getSubKind() == RhsLoc.getSubKind())) {
7564d5b824eSVince Bridgers assert(RhsBitwidth == LhsBitwidth &&
7574d5b824eSVince Bridgers "RhsLoc and LhsLoc bitwidth must be same!");
7584d5b824eSVince Bridgers }
7594d5b824eSVince Bridgers }
7604d5b824eSVince Bridgers
761fa0734ecSArgyrios Kyrtzidis // FIXME: all this logic will change if/when we have MemRegion::getLocation().
evalBinOpLL(ProgramStateRef state,BinaryOperator::Opcode op,Loc lhs,Loc rhs,QualType resultTy)76249b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
763fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode op,
764fa0734ecSArgyrios Kyrtzidis Loc lhs, Loc rhs,
765fa0734ecSArgyrios Kyrtzidis QualType resultTy) {
7664d5b824eSVince Bridgers
7674d5b824eSVince Bridgers // Assert that bitwidth of lhs and rhs are the same.
7684d5b824eSVince Bridgers // This can happen if two different address spaces are used,
7694d5b824eSVince Bridgers // and the bitwidths of the address spaces are different.
7704d5b824eSVince Bridgers // See LIT case clang/test/Analysis/cstring-checker-addressspace.c
7714d5b824eSVince Bridgers // FIXME: See comment above in the function assertEqualBitWidths
7724d5b824eSVince Bridgers assertEqualBitWidths(state, rhs, lhs);
7734d5b824eSVince Bridgers
774fa0734ecSArgyrios Kyrtzidis // Only comparisons and subtractions are valid operations on two pointers.
775fa0734ecSArgyrios Kyrtzidis // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
776fa0734ecSArgyrios Kyrtzidis // However, if a pointer is casted to an integer, evalBinOpNN may end up
777fa0734ecSArgyrios Kyrtzidis // calling this function with another operation (PR7527). We don't attempt to
778fa0734ecSArgyrios Kyrtzidis // model this for now, but it could be useful, particularly when the
779fa0734ecSArgyrios Kyrtzidis // "location" is actually an integer value that's been passed through a void*.
780fa0734ecSArgyrios Kyrtzidis if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
781fa0734ecSArgyrios Kyrtzidis return UnknownVal();
782fa0734ecSArgyrios Kyrtzidis
783fa0734ecSArgyrios Kyrtzidis // Special cases for when both sides are identical.
784fa0734ecSArgyrios Kyrtzidis if (lhs == rhs) {
785fa0734ecSArgyrios Kyrtzidis switch (op) {
786fa0734ecSArgyrios Kyrtzidis default:
78783d382b1SDavid Blaikie llvm_unreachable("Unimplemented operation for two identical values");
788fa0734ecSArgyrios Kyrtzidis case BO_Sub:
789fa0734ecSArgyrios Kyrtzidis return makeZeroVal(resultTy);
790fa0734ecSArgyrios Kyrtzidis case BO_EQ:
791fa0734ecSArgyrios Kyrtzidis case BO_LE:
792fa0734ecSArgyrios Kyrtzidis case BO_GE:
793fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy);
794fa0734ecSArgyrios Kyrtzidis case BO_NE:
795fa0734ecSArgyrios Kyrtzidis case BO_LT:
796fa0734ecSArgyrios Kyrtzidis case BO_GT:
797fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy);
798fa0734ecSArgyrios Kyrtzidis }
799fa0734ecSArgyrios Kyrtzidis }
800fa0734ecSArgyrios Kyrtzidis
801fa0734ecSArgyrios Kyrtzidis switch (lhs.getSubKind()) {
802fa0734ecSArgyrios Kyrtzidis default:
80383d382b1SDavid Blaikie llvm_unreachable("Ordering not implemented for this Loc.");
804fa0734ecSArgyrios Kyrtzidis
805fa0734ecSArgyrios Kyrtzidis case loc::GotoLabelKind:
806fa0734ecSArgyrios Kyrtzidis // The only thing we know about labels is that they're non-null.
807fa0734ecSArgyrios Kyrtzidis if (rhs.isZeroConstant()) {
808fa0734ecSArgyrios Kyrtzidis switch (op) {
809fa0734ecSArgyrios Kyrtzidis default:
810fa0734ecSArgyrios Kyrtzidis break;
811fa0734ecSArgyrios Kyrtzidis case BO_Sub:
81201ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{});
813fa0734ecSArgyrios Kyrtzidis case BO_EQ:
814fa0734ecSArgyrios Kyrtzidis case BO_LE:
815fa0734ecSArgyrios Kyrtzidis case BO_LT:
816fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy);
817fa0734ecSArgyrios Kyrtzidis case BO_NE:
818fa0734ecSArgyrios Kyrtzidis case BO_GT:
819fa0734ecSArgyrios Kyrtzidis case BO_GE:
820fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy);
821fa0734ecSArgyrios Kyrtzidis }
822fa0734ecSArgyrios Kyrtzidis }
823fa0734ecSArgyrios Kyrtzidis // There may be two labels for the same location, and a function region may
824fa0734ecSArgyrios Kyrtzidis // have the same address as a label at the start of the function (depending
825fa0734ecSArgyrios Kyrtzidis // on the ABI).
826fa0734ecSArgyrios Kyrtzidis // FIXME: we can probably do a comparison against other MemRegions, though.
827fa0734ecSArgyrios Kyrtzidis // FIXME: is there a way to tell if two labels refer to the same location?
828fa0734ecSArgyrios Kyrtzidis return UnknownVal();
829fa0734ecSArgyrios Kyrtzidis
830fa0734ecSArgyrios Kyrtzidis case loc::ConcreteIntKind: {
831f6eab437SBalazs Benics auto L = lhs.castAs<loc::ConcreteInt>();
832f6eab437SBalazs Benics
833fa0734ecSArgyrios Kyrtzidis // If one of the operands is a symbol and the other is a constant,
834fa0734ecSArgyrios Kyrtzidis // build an expression for use by the constraint manager.
835fa0734ecSArgyrios Kyrtzidis if (SymbolRef rSym = rhs.getAsLocSymbol()) {
836c0402c69SDominic Chen // We can only build expressions with symbols on the left,
837c0402c69SDominic Chen // so we need a reversible operator.
838c70f1d63SRichard Smith if (!BinaryOperator::isComparisonOp(op) || op == BO_Cmp)
839c0402c69SDominic Chen return UnknownVal();
84035610d21SDominic Chen
841604d0bbbSJordan Rose op = BinaryOperator::reverseComparisonOp(op);
842f6eab437SBalazs Benics return makeNonLoc(rSym, op, L.getValue(), resultTy);
843fa0734ecSArgyrios Kyrtzidis }
844fa0734ecSArgyrios Kyrtzidis
845fa0734ecSArgyrios Kyrtzidis // If both operands are constants, just perform the operation.
84605785d16SDavid Blaikie if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
847f6eab437SBalazs Benics assert(BinaryOperator::isComparisonOp(op) || op == BO_Sub);
8488eca04b2SJordan Rose
849f6eab437SBalazs Benics if (const auto *ResultInt =
850f6eab437SBalazs Benics BasicVals.evalAPSInt(op, L.getValue(), rInt->getValue()))
851f6eab437SBalazs Benics return evalCast(nonloc::ConcreteInt(*ResultInt), resultTy, QualType{});
852fa0734ecSArgyrios Kyrtzidis return UnknownVal();
853fa0734ecSArgyrios Kyrtzidis }
854fa0734ecSArgyrios Kyrtzidis
855fa0734ecSArgyrios Kyrtzidis // Special case comparisons against NULL.
856fa0734ecSArgyrios Kyrtzidis // This must come after the test if the RHS is a symbol, which is used to
857fa0734ecSArgyrios Kyrtzidis // build constraints. The address of any non-symbolic region is guaranteed
858fa0734ecSArgyrios Kyrtzidis // to be non-NULL, as is any label.
859*96ccb690SBalazs Benics assert((isa<loc::MemRegionVal, loc::GotoLabel>(rhs)));
860fa0734ecSArgyrios Kyrtzidis if (lhs.isZeroConstant()) {
861fa0734ecSArgyrios Kyrtzidis switch (op) {
862fa0734ecSArgyrios Kyrtzidis default:
863fa0734ecSArgyrios Kyrtzidis break;
864fa0734ecSArgyrios Kyrtzidis case BO_EQ:
865fa0734ecSArgyrios Kyrtzidis case BO_GT:
866fa0734ecSArgyrios Kyrtzidis case BO_GE:
867fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy);
868fa0734ecSArgyrios Kyrtzidis case BO_NE:
869fa0734ecSArgyrios Kyrtzidis case BO_LT:
870fa0734ecSArgyrios Kyrtzidis case BO_LE:
871fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy);
872fa0734ecSArgyrios Kyrtzidis }
873fa0734ecSArgyrios Kyrtzidis }
874fa0734ecSArgyrios Kyrtzidis
875fa0734ecSArgyrios Kyrtzidis // Comparing an arbitrary integer to a region or label address is
876fa0734ecSArgyrios Kyrtzidis // completely unknowable.
877fa0734ecSArgyrios Kyrtzidis return UnknownVal();
878fa0734ecSArgyrios Kyrtzidis }
87973f018e3SArtem Dergachev case loc::MemRegionValKind: {
88005785d16SDavid Blaikie if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
881fa0734ecSArgyrios Kyrtzidis // If one of the operands is a symbol and the other is a constant,
882fa0734ecSArgyrios Kyrtzidis // build an expression for use by the constraint manager.
883f4963ff1SAlexander Shaposhnikov if (SymbolRef lSym = lhs.getAsLocSymbol(true)) {
884f4963ff1SAlexander Shaposhnikov if (BinaryOperator::isComparisonOp(op))
885fa0734ecSArgyrios Kyrtzidis return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
886f4963ff1SAlexander Shaposhnikov return UnknownVal();
887f4963ff1SAlexander Shaposhnikov }
888fa0734ecSArgyrios Kyrtzidis // Special case comparisons to NULL.
889fa0734ecSArgyrios Kyrtzidis // This must come after the test if the LHS is a symbol, which is used to
890fa0734ecSArgyrios Kyrtzidis // build constraints. The address of any non-symbolic region is guaranteed
891fa0734ecSArgyrios Kyrtzidis // to be non-NULL.
892fa0734ecSArgyrios Kyrtzidis if (rInt->isZeroConstant()) {
893acd080b9SJordan Rose if (op == BO_Sub)
89401ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{});
895acd080b9SJordan Rose
896acd080b9SJordan Rose if (BinaryOperator::isComparisonOp(op)) {
897acd080b9SJordan Rose QualType boolType = getContext().BoolTy;
89801ddfa95SDenys Petrov NonLoc l = evalCast(lhs, boolType, QualType{}).castAs<NonLoc>();
899acd080b9SJordan Rose NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>();
900acd080b9SJordan Rose return evalBinOpNN(state, op, l, r, resultTy);
901fa0734ecSArgyrios Kyrtzidis }
902fa0734ecSArgyrios Kyrtzidis }
903fa0734ecSArgyrios Kyrtzidis
904fa0734ecSArgyrios Kyrtzidis // Comparing a region to an arbitrary integer is completely unknowable.
905fa0734ecSArgyrios Kyrtzidis return UnknownVal();
906fa0734ecSArgyrios Kyrtzidis }
907fa0734ecSArgyrios Kyrtzidis
908fa0734ecSArgyrios Kyrtzidis // Get both values as regions, if possible.
909fa0734ecSArgyrios Kyrtzidis const MemRegion *LeftMR = lhs.getAsRegion();
91073f018e3SArtem Dergachev assert(LeftMR && "MemRegionValKind SVal doesn't have a region!");
911fa0734ecSArgyrios Kyrtzidis
912fa0734ecSArgyrios Kyrtzidis const MemRegion *RightMR = rhs.getAsRegion();
913fa0734ecSArgyrios Kyrtzidis if (!RightMR)
914fa0734ecSArgyrios Kyrtzidis // The RHS is probably a label, which in theory could address a region.
915fa0734ecSArgyrios Kyrtzidis // FIXME: we can probably make a more useful statement about non-code
916fa0734ecSArgyrios Kyrtzidis // regions, though.
917fa0734ecSArgyrios Kyrtzidis return UnknownVal();
918fa0734ecSArgyrios Kyrtzidis
919fa0734ecSArgyrios Kyrtzidis const MemRegion *LeftBase = LeftMR->getBaseRegion();
920fa0734ecSArgyrios Kyrtzidis const MemRegion *RightBase = RightMR->getBaseRegion();
9213b4c3ea2SJordan Rose const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
9223b4c3ea2SJordan Rose const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
9233b4c3ea2SJordan Rose const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
9243563fde6SAnna Zaks
9253563fde6SAnna Zaks // If the two regions are from different known memory spaces they cannot be
9263563fde6SAnna Zaks // equal. Also, assume that no symbolic region (whose memory space is
9273563fde6SAnna Zaks // unknown) is on the stack.
9283563fde6SAnna Zaks if (LeftMS != RightMS &&
9293563fde6SAnna Zaks ((LeftMS != UnknownMS && RightMS != UnknownMS) ||
9303563fde6SAnna Zaks (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
931fa0734ecSArgyrios Kyrtzidis switch (op) {
932fa0734ecSArgyrios Kyrtzidis default:
933fa0734ecSArgyrios Kyrtzidis return UnknownVal();
934fa0734ecSArgyrios Kyrtzidis case BO_EQ:
935fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy);
936fa0734ecSArgyrios Kyrtzidis case BO_NE:
937fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy);
938fa0734ecSArgyrios Kyrtzidis }
939fa0734ecSArgyrios Kyrtzidis }
940fa0734ecSArgyrios Kyrtzidis
9413563fde6SAnna Zaks // If both values wrap regions, see if they're from different base regions.
9423563fde6SAnna Zaks // Note, heap base symbolic regions are assumed to not alias with
9433563fde6SAnna Zaks // each other; for example, we assume that malloc returns different address
9443563fde6SAnna Zaks // on each invocation.
945aacc03c9SArtem Dergachev // FIXME: ObjC object pointers always reside on the heap, but currently
946aacc03c9SArtem Dergachev // we treat their memory space as unknown, because symbolic pointers
947aacc03c9SArtem Dergachev // to ObjC objects may alias. There should be a way to construct
948aacc03c9SArtem Dergachev // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker
949aacc03c9SArtem Dergachev // guesses memory space for ObjC object pointers manually instead of
950aacc03c9SArtem Dergachev // relying on us.
9513563fde6SAnna Zaks if (LeftBase != RightBase &&
9523563fde6SAnna Zaks ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
953a7dcc996SAnna Zaks (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
9549d96f843STed Kremenek switch (op) {
9559d96f843STed Kremenek default:
9563563fde6SAnna Zaks return UnknownVal();
9579d96f843STed Kremenek case BO_EQ:
9589d96f843STed Kremenek return makeTruthVal(false, resultTy);
9599d96f843STed Kremenek case BO_NE:
9609d96f843STed Kremenek return makeTruthVal(true, resultTy);
9619d96f843STed Kremenek }
9629d96f843STed Kremenek }
963fa0734ecSArgyrios Kyrtzidis
964bac964e1SAnna Zaks // Handle special cases for when both regions are element regions.
965fa0734ecSArgyrios Kyrtzidis const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
966bac964e1SAnna Zaks const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR);
967bac964e1SAnna Zaks if (RightER && LeftER) {
968fa0734ecSArgyrios Kyrtzidis // Next, see if the two ERs have the same super-region and matching types.
969fa0734ecSArgyrios Kyrtzidis // FIXME: This should do something useful even if the types don't match,
970fa0734ecSArgyrios Kyrtzidis // though if both indexes are constant the RegionRawOffset path will
971fa0734ecSArgyrios Kyrtzidis // give the correct answer.
972fa0734ecSArgyrios Kyrtzidis if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
973fa0734ecSArgyrios Kyrtzidis LeftER->getElementType() == RightER->getElementType()) {
974fa0734ecSArgyrios Kyrtzidis // Get the left index and cast it to the correct type.
975fa0734ecSArgyrios Kyrtzidis // If the index is unknown or undefined, bail out here.
976fa0734ecSArgyrios Kyrtzidis SVal LeftIndexVal = LeftER->getIndex();
97705785d16SDavid Blaikie Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
978fa0734ecSArgyrios Kyrtzidis if (!LeftIndex)
979fa0734ecSArgyrios Kyrtzidis return UnknownVal();
98001ddfa95SDenys Petrov LeftIndexVal = evalCast(*LeftIndex, ArrayIndexTy, QualType{});
9812fdacbc5SDavid Blaikie LeftIndex = LeftIndexVal.getAs<NonLoc>();
982fa0734ecSArgyrios Kyrtzidis if (!LeftIndex)
983fa0734ecSArgyrios Kyrtzidis return UnknownVal();
984fa0734ecSArgyrios Kyrtzidis
985fa0734ecSArgyrios Kyrtzidis // Do the same for the right index.
986fa0734ecSArgyrios Kyrtzidis SVal RightIndexVal = RightER->getIndex();
98705785d16SDavid Blaikie Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
988fa0734ecSArgyrios Kyrtzidis if (!RightIndex)
989fa0734ecSArgyrios Kyrtzidis return UnknownVal();
99001ddfa95SDenys Petrov RightIndexVal = evalCast(*RightIndex, ArrayIndexTy, QualType{});
9912fdacbc5SDavid Blaikie RightIndex = RightIndexVal.getAs<NonLoc>();
992fa0734ecSArgyrios Kyrtzidis if (!RightIndex)
993fa0734ecSArgyrios Kyrtzidis return UnknownVal();
994fa0734ecSArgyrios Kyrtzidis
995fa0734ecSArgyrios Kyrtzidis // Actually perform the operation.
996fa0734ecSArgyrios Kyrtzidis // evalBinOpNN expects the two indexes to already be the right type.
997fa0734ecSArgyrios Kyrtzidis return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
998fa0734ecSArgyrios Kyrtzidis }
999bac964e1SAnna Zaks }
1000fa0734ecSArgyrios Kyrtzidis
1001bac964e1SAnna Zaks // Special handling of the FieldRegions, even with symbolic offsets.
1002bac964e1SAnna Zaks const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
1003bac964e1SAnna Zaks const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR);
1004bac964e1SAnna Zaks if (RightFR && LeftFR) {
1005bac964e1SAnna Zaks SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy,
1006bac964e1SAnna Zaks *this);
1007bac964e1SAnna Zaks if (!R.isUnknown())
1008bac964e1SAnna Zaks return R;
1009bac964e1SAnna Zaks }
1010bac964e1SAnna Zaks
1011bac964e1SAnna Zaks // Compare the regions using the raw offsets.
1012bac964e1SAnna Zaks RegionOffset LeftOffset = LeftMR->getAsOffset();
1013bac964e1SAnna Zaks RegionOffset RightOffset = RightMR->getAsOffset();
1014fa0734ecSArgyrios Kyrtzidis
10150dbb783cSCraig Topper if (LeftOffset.getRegion() != nullptr &&
1016bac964e1SAnna Zaks LeftOffset.getRegion() == RightOffset.getRegion() &&
1017bac964e1SAnna Zaks !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) {
1018bac964e1SAnna Zaks int64_t left = LeftOffset.getOffset();
1019bac964e1SAnna Zaks int64_t right = RightOffset.getOffset();
1020fa0734ecSArgyrios Kyrtzidis
1021fa0734ecSArgyrios Kyrtzidis switch (op) {
1022fa0734ecSArgyrios Kyrtzidis default:
1023fa0734ecSArgyrios Kyrtzidis return UnknownVal();
1024fa0734ecSArgyrios Kyrtzidis case BO_LT:
1025fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left < right, resultTy);
1026fa0734ecSArgyrios Kyrtzidis case BO_GT:
1027fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left > right, resultTy);
1028fa0734ecSArgyrios Kyrtzidis case BO_LE:
1029fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left <= right, resultTy);
1030fa0734ecSArgyrios Kyrtzidis case BO_GE:
1031fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left >= right, resultTy);
1032fa0734ecSArgyrios Kyrtzidis case BO_EQ:
1033fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left == right, resultTy);
1034fa0734ecSArgyrios Kyrtzidis case BO_NE:
1035fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left != right, resultTy);
1036fa0734ecSArgyrios Kyrtzidis }
1037fa0734ecSArgyrios Kyrtzidis }
1038fa0734ecSArgyrios Kyrtzidis
10393b4c3ea2SJordan Rose // At this point we're not going to get a good answer, but we can try
10403b4c3ea2SJordan Rose // conjuring an expression instead.
10413b4c3ea2SJordan Rose SymbolRef LHSSym = lhs.getAsLocSymbol();
10423b4c3ea2SJordan Rose SymbolRef RHSSym = rhs.getAsLocSymbol();
10433b4c3ea2SJordan Rose if (LHSSym && RHSSym)
10443b4c3ea2SJordan Rose return makeNonLoc(LHSSym, op, RHSSym, resultTy);
10453b4c3ea2SJordan Rose
1046fa0734ecSArgyrios Kyrtzidis // If we get here, we have no way of comparing the regions.
1047fa0734ecSArgyrios Kyrtzidis return UnknownVal();
1048fa0734ecSArgyrios Kyrtzidis }
1049fa0734ecSArgyrios Kyrtzidis }
1050fa0734ecSArgyrios Kyrtzidis }
1051fa0734ecSArgyrios Kyrtzidis
evalBinOpLN(ProgramStateRef state,BinaryOperator::Opcode op,Loc lhs,NonLoc rhs,QualType resultTy)105249b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
10539cbfdde2SValeriy Savchenko BinaryOperator::Opcode op, Loc lhs,
10549cbfdde2SValeriy Savchenko NonLoc rhs, QualType resultTy) {
105564c01f7bSDevin Coughlin if (op >= BO_PtrMemD && op <= BO_PtrMemI) {
105664c01f7bSDevin Coughlin if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) {
105764c01f7bSDevin Coughlin if (PTMSV->isNullMemberPointer())
105864c01f7bSDevin Coughlin return UndefinedVal();
10599cbfdde2SValeriy Savchenko
10609cbfdde2SValeriy Savchenko auto getFieldLValue = [&](const auto *FD) -> SVal {
106164c01f7bSDevin Coughlin SVal Result = lhs;
106264c01f7bSDevin Coughlin
106364c01f7bSDevin Coughlin for (const auto &I : *PTMSV)
106464c01f7bSDevin Coughlin Result = StateMgr.getStoreManager().evalDerivedToBase(
106564c01f7bSDevin Coughlin Result, I->getType(), I->isVirtual());
10669cbfdde2SValeriy Savchenko
106764c01f7bSDevin Coughlin return state->getLValue(FD, Result);
10689cbfdde2SValeriy Savchenko };
10699cbfdde2SValeriy Savchenko
10709cbfdde2SValeriy Savchenko if (const auto *FD = PTMSV->getDeclAs<FieldDecl>()) {
10719cbfdde2SValeriy Savchenko return getFieldLValue(FD);
10729cbfdde2SValeriy Savchenko }
10739cbfdde2SValeriy Savchenko if (const auto *FD = PTMSV->getDeclAs<IndirectFieldDecl>()) {
10749cbfdde2SValeriy Savchenko return getFieldLValue(FD);
107564c01f7bSDevin Coughlin }
107664c01f7bSDevin Coughlin }
107764c01f7bSDevin Coughlin
107864c01f7bSDevin Coughlin return rhs;
107964c01f7bSDevin Coughlin }
108064c01f7bSDevin Coughlin
1081686df322SJordan Rose assert(!BinaryOperator::isComparisonOp(op) &&
1082686df322SJordan Rose "arguments to comparison ops must be of the same type");
1083fa0734ecSArgyrios Kyrtzidis
1084fa0734ecSArgyrios Kyrtzidis // Special case: rhs is a zero constant.
1085fa0734ecSArgyrios Kyrtzidis if (rhs.isZeroConstant())
1086fa0734ecSArgyrios Kyrtzidis return lhs;
1087fa0734ecSArgyrios Kyrtzidis
108821524676SGabor Horvath // Perserve the null pointer so that it can be found by the DerefChecker.
108921524676SGabor Horvath if (lhs.isZeroConstant())
109021524676SGabor Horvath return lhs;
109121524676SGabor Horvath
1092fa0734ecSArgyrios Kyrtzidis // We are dealing with pointer arithmetic.
1093fa0734ecSArgyrios Kyrtzidis
1094fa0734ecSArgyrios Kyrtzidis // Handle pointer arithmetic on constant values.
109505785d16SDavid Blaikie if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) {
109605785d16SDavid Blaikie if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) {
1097fa0734ecSArgyrios Kyrtzidis const llvm::APSInt &leftI = lhsInt->getValue();
1098fa0734ecSArgyrios Kyrtzidis assert(leftI.isUnsigned());
1099fa0734ecSArgyrios Kyrtzidis llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
1100fa0734ecSArgyrios Kyrtzidis
1101fa0734ecSArgyrios Kyrtzidis // Convert the bitwidth of rightI. This should deal with overflow
1102fa0734ecSArgyrios Kyrtzidis // since we are dealing with concrete values.
1103fa0734ecSArgyrios Kyrtzidis rightI = rightI.extOrTrunc(leftI.getBitWidth());
1104fa0734ecSArgyrios Kyrtzidis
1105fa0734ecSArgyrios Kyrtzidis // Offset the increment by the pointer size.
1106fa0734ecSArgyrios Kyrtzidis llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
110721524676SGabor Horvath QualType pointeeType = resultTy->getPointeeType();
110821524676SGabor Horvath Multiplicand = getContext().getTypeSizeInChars(pointeeType).getQuantity();
1109fa0734ecSArgyrios Kyrtzidis rightI *= Multiplicand;
1110fa0734ecSArgyrios Kyrtzidis
1111fa0734ecSArgyrios Kyrtzidis // Compute the adjusted pointer.
1112fa0734ecSArgyrios Kyrtzidis switch (op) {
1113fa0734ecSArgyrios Kyrtzidis case BO_Add:
1114fa0734ecSArgyrios Kyrtzidis rightI = leftI + rightI;
1115fa0734ecSArgyrios Kyrtzidis break;
1116fa0734ecSArgyrios Kyrtzidis case BO_Sub:
1117fa0734ecSArgyrios Kyrtzidis rightI = leftI - rightI;
1118fa0734ecSArgyrios Kyrtzidis break;
1119fa0734ecSArgyrios Kyrtzidis default:
1120fa0734ecSArgyrios Kyrtzidis llvm_unreachable("Invalid pointer arithmetic operation");
1121fa0734ecSArgyrios Kyrtzidis }
1122fa0734ecSArgyrios Kyrtzidis return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
1123fa0734ecSArgyrios Kyrtzidis }
1124fa0734ecSArgyrios Kyrtzidis }
1125fa0734ecSArgyrios Kyrtzidis
1126fa0734ecSArgyrios Kyrtzidis // Handle cases where 'lhs' is a region.
1127fa0734ecSArgyrios Kyrtzidis if (const MemRegion *region = lhs.getAsRegion()) {
11282fdacbc5SDavid Blaikie rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
1129fa0734ecSArgyrios Kyrtzidis SVal index = UnknownVal();
11306dd11048SArtem Dergachev const SubRegion *superR = nullptr;
11317333a9eaSArtem Dergachev // We need to know the type of the pointer in order to add an integer to it.
11327333a9eaSArtem Dergachev // Depending on the type, different amount of bytes is added.
1133fa0734ecSArgyrios Kyrtzidis QualType elementType;
1134fa0734ecSArgyrios Kyrtzidis
1135fa0734ecSArgyrios Kyrtzidis if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
113657a4a152STed Kremenek assert(op == BO_Add || op == BO_Sub);
113757a4a152STed Kremenek index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
1138fa0734ecSArgyrios Kyrtzidis getArrayIndexType());
11396dd11048SArtem Dergachev superR = cast<SubRegion>(elemReg->getSuperRegion());
1140fa0734ecSArgyrios Kyrtzidis elementType = elemReg->getElementType();
1141fa0734ecSArgyrios Kyrtzidis }
1142fa0734ecSArgyrios Kyrtzidis else if (isa<SubRegion>(region)) {
1143c4b28a8fSGabor Horvath assert(op == BO_Add || op == BO_Sub);
1144c4b28a8fSGabor Horvath index = (op == BO_Add) ? rhs : evalMinus(rhs);
11456dd11048SArtem Dergachev superR = cast<SubRegion>(region);
11467333a9eaSArtem Dergachev // TODO: Is this actually reliable? Maybe improving our MemRegion
11477333a9eaSArtem Dergachev // hierarchy to provide typed regions for all non-void pointers would be
11487333a9eaSArtem Dergachev // better. For instance, we cannot extend this towards LocAsInteger
11497333a9eaSArtem Dergachev // operations, where result type of the expression is integer.
1150d1a08b6eSJordan Rose if (resultTy->isAnyPointerType())
1151d1a08b6eSJordan Rose elementType = resultTy->getPointeeType();
1152fa0734ecSArgyrios Kyrtzidis }
1153fa0734ecSArgyrios Kyrtzidis
1154df1bb8a6SArtem Dergachev // Represent arithmetic on void pointers as arithmetic on char pointers.
1155df1bb8a6SArtem Dergachev // It is fine when a TypedValueRegion of char value type represents
1156df1bb8a6SArtem Dergachev // a void pointer. Note that arithmetic on void pointers is a GCC extension.
1157df1bb8a6SArtem Dergachev if (elementType->isVoidType())
1158df1bb8a6SArtem Dergachev elementType = getContext().CharTy;
1159df1bb8a6SArtem Dergachev
116005785d16SDavid Blaikie if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) {
1161fa0734ecSArgyrios Kyrtzidis return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
1162fa0734ecSArgyrios Kyrtzidis superR, getContext()));
1163fa0734ecSArgyrios Kyrtzidis }
1164fa0734ecSArgyrios Kyrtzidis }
1165fa0734ecSArgyrios Kyrtzidis return UnknownVal();
1166fa0734ecSArgyrios Kyrtzidis }
1167fa0734ecSArgyrios Kyrtzidis
getConstValue(ProgramStateRef state,SVal V)1168bc2c759aSGabor Marton const llvm::APSInt *SimpleSValBuilder::getConstValue(ProgramStateRef state,
1169fa0734ecSArgyrios Kyrtzidis SVal V) {
1170fa0734ecSArgyrios Kyrtzidis if (V.isUnknownOrUndef())
11710dbb783cSCraig Topper return nullptr;
1172fa0734ecSArgyrios Kyrtzidis
117305785d16SDavid Blaikie if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
1174fa0734ecSArgyrios Kyrtzidis return &X->getValue();
1175fa0734ecSArgyrios Kyrtzidis
117605785d16SDavid Blaikie if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
1177fa0734ecSArgyrios Kyrtzidis return &X->getValue();
1178fa0734ecSArgyrios Kyrtzidis
1179fa0734ecSArgyrios Kyrtzidis if (SymbolRef Sym = V.getAsSymbol())
1180244e1d7dSTed Kremenek return state->getConstraintManager().getSymVal(state, Sym);
1181fa0734ecSArgyrios Kyrtzidis
11820dbb783cSCraig Topper return nullptr;
1183fa0734ecSArgyrios Kyrtzidis }
118412294f8dSArtem Dergachev
getKnownValue(ProgramStateRef state,SVal V)1185bc2c759aSGabor Marton const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
1186bc2c759aSGabor Marton SVal V) {
1187bc2c759aSGabor Marton return getConstValue(state, simplifySVal(state, V));
1188bc2c759aSGabor Marton }
1189bc2c759aSGabor Marton
simplifyUntilFixpoint(ProgramStateRef State,SVal Val)1190978431e8SGabor Marton SVal SimpleSValBuilder::simplifyUntilFixpoint(ProgramStateRef State, SVal Val) {
1191978431e8SGabor Marton SVal SimplifiedVal = simplifySValOnce(State, Val);
1192978431e8SGabor Marton while (SimplifiedVal != Val) {
1193978431e8SGabor Marton Val = SimplifiedVal;
1194978431e8SGabor Marton SimplifiedVal = simplifySValOnce(State, Val);
1195978431e8SGabor Marton }
1196978431e8SGabor Marton return SimplifiedVal;
1197978431e8SGabor Marton }
1198978431e8SGabor Marton
simplifySVal(ProgramStateRef State,SVal V)119912294f8dSArtem Dergachev SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) {
1200978431e8SGabor Marton return simplifyUntilFixpoint(State, V);
1201978431e8SGabor Marton }
1202978431e8SGabor Marton
simplifySValOnce(ProgramStateRef State,SVal V)1203978431e8SGabor Marton SVal SimpleSValBuilder::simplifySValOnce(ProgramStateRef State, SVal V) {
120412294f8dSArtem Dergachev // For now, this function tries to constant-fold symbols inside a
120512294f8dSArtem Dergachev // nonloc::SymbolVal, and does nothing else. More simplifications should
120612294f8dSArtem Dergachev // be possible, such as constant-folding an index in an ElementRegion.
120712294f8dSArtem Dergachev
120812294f8dSArtem Dergachev class Simplifier : public FullSValVisitor<Simplifier, SVal> {
120912294f8dSArtem Dergachev ProgramStateRef State;
121012294f8dSArtem Dergachev SValBuilder &SVB;
121112294f8dSArtem Dergachev
121222746d7dSArtem Dergachev // Cache results for the lifetime of the Simplifier. Results change every
121322746d7dSArtem Dergachev // time new constraints are added to the program state, which is the whole
121422746d7dSArtem Dergachev // point of simplifying, and for that very reason it's pointless to maintain
121522746d7dSArtem Dergachev // the same cache for the duration of the whole analysis.
121622746d7dSArtem Dergachev llvm::DenseMap<SymbolRef, SVal> Cached;
121722746d7dSArtem Dergachev
121816a1f64cSArtem Dergachev static bool isUnchanged(SymbolRef Sym, SVal Val) {
121916a1f64cSArtem Dergachev return Sym == Val.getAsSymbol();
122016a1f64cSArtem Dergachev }
122116a1f64cSArtem Dergachev
12229fe9a95fSArtem Dergachev SVal cache(SymbolRef Sym, SVal V) {
12239fe9a95fSArtem Dergachev Cached[Sym] = V;
12249fe9a95fSArtem Dergachev return V;
12259fe9a95fSArtem Dergachev }
12269fe9a95fSArtem Dergachev
12279fe9a95fSArtem Dergachev SVal skip(SymbolRef Sym) {
12289fe9a95fSArtem Dergachev return cache(Sym, SVB.makeSymbolVal(Sym));
12299fe9a95fSArtem Dergachev }
12309fe9a95fSArtem Dergachev
12310a17896fSGabor Marton // Return the known const value for the Sym if available, or return Undef
12320a17896fSGabor Marton // otherwise.
12330a17896fSGabor Marton SVal getConst(SymbolRef Sym) {
12340a17896fSGabor Marton const llvm::APSInt *Const =
12350a17896fSGabor Marton State->getConstraintManager().getSymVal(State, Sym);
12360a17896fSGabor Marton if (Const)
12370a17896fSGabor Marton return Loc::isLocType(Sym->getType()) ? (SVal)SVB.makeIntLocVal(*Const)
12380a17896fSGabor Marton : (SVal)SVB.makeIntVal(*Const);
12390a17896fSGabor Marton return UndefinedVal();
12400a17896fSGabor Marton }
12410a17896fSGabor Marton
12420a17896fSGabor Marton SVal getConstOrVisit(SymbolRef Sym) {
12430a17896fSGabor Marton const SVal Ret = getConst(Sym);
12440a17896fSGabor Marton if (Ret.isUndef())
12450a17896fSGabor Marton return Visit(Sym);
12460a17896fSGabor Marton return Ret;
12470a17896fSGabor Marton }
12480a17896fSGabor Marton
124912294f8dSArtem Dergachev public:
125012294f8dSArtem Dergachev Simplifier(ProgramStateRef State)
125112294f8dSArtem Dergachev : State(State), SVB(State->getStateManager().getSValBuilder()) {}
125212294f8dSArtem Dergachev
125312294f8dSArtem Dergachev SVal VisitSymbolData(const SymbolData *S) {
12549fe9a95fSArtem Dergachev // No cache here.
125512294f8dSArtem Dergachev if (const llvm::APSInt *I =
1256bc2c759aSGabor Marton State->getConstraintManager().getSymVal(State, S))
125712294f8dSArtem Dergachev return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I)
125812294f8dSArtem Dergachev : (SVal)SVB.makeIntVal(*I);
125916a1f64cSArtem Dergachev return SVB.makeSymbolVal(S);
126012294f8dSArtem Dergachev }
126112294f8dSArtem Dergachev
126212294f8dSArtem Dergachev SVal VisitSymIntExpr(const SymIntExpr *S) {
126322746d7dSArtem Dergachev auto I = Cached.find(S);
126422746d7dSArtem Dergachev if (I != Cached.end())
126522746d7dSArtem Dergachev return I->second;
126622746d7dSArtem Dergachev
12670a17896fSGabor Marton SVal LHS = getConstOrVisit(S->getLHS());
12689fe9a95fSArtem Dergachev if (isUnchanged(S->getLHS(), LHS))
12699fe9a95fSArtem Dergachev return skip(S);
12709fe9a95fSArtem Dergachev
127112294f8dSArtem Dergachev SVal RHS;
127212294f8dSArtem Dergachev // By looking at the APSInt in the right-hand side of S, we cannot
127312294f8dSArtem Dergachev // figure out if it should be treated as a Loc or as a NonLoc.
127412294f8dSArtem Dergachev // So make our guess by recalling that we cannot multiply pointers
127512294f8dSArtem Dergachev // or compare a pointer to an integer.
127612294f8dSArtem Dergachev if (Loc::isLocType(S->getLHS()->getType()) &&
127712294f8dSArtem Dergachev BinaryOperator::isComparisonOp(S->getOpcode())) {
127812294f8dSArtem Dergachev // The usual conversion of $sym to &SymRegion{$sym}, as they have
127912294f8dSArtem Dergachev // the same meaning for Loc-type symbols, but the latter form
128012294f8dSArtem Dergachev // is preferred in SVal computations for being Loc itself.
128112294f8dSArtem Dergachev if (SymbolRef Sym = LHS.getAsSymbol()) {
128212294f8dSArtem Dergachev assert(Loc::isLocType(Sym->getType()));
128312294f8dSArtem Dergachev LHS = SVB.makeLoc(Sym);
128412294f8dSArtem Dergachev }
128512294f8dSArtem Dergachev RHS = SVB.makeIntLocVal(S->getRHS());
128612294f8dSArtem Dergachev } else {
128712294f8dSArtem Dergachev RHS = SVB.makeIntVal(S->getRHS());
128812294f8dSArtem Dergachev }
128922746d7dSArtem Dergachev
12909fe9a95fSArtem Dergachev return cache(
12919fe9a95fSArtem Dergachev S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
129212294f8dSArtem Dergachev }
129312294f8dSArtem Dergachev
1294ffc32efdSGabor Marton SVal VisitIntSymExpr(const IntSymExpr *S) {
1295ffc32efdSGabor Marton auto I = Cached.find(S);
1296ffc32efdSGabor Marton if (I != Cached.end())
1297ffc32efdSGabor Marton return I->second;
1298ffc32efdSGabor Marton
12990a17896fSGabor Marton SVal RHS = getConstOrVisit(S->getRHS());
1300ffc32efdSGabor Marton if (isUnchanged(S->getRHS(), RHS))
1301ffc32efdSGabor Marton return skip(S);
13020a17896fSGabor Marton
1303ffc32efdSGabor Marton SVal LHS = SVB.makeIntVal(S->getLHS());
1304ffc32efdSGabor Marton return cache(
1305ffc32efdSGabor Marton S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
1306ffc32efdSGabor Marton }
1307ffc32efdSGabor Marton
130812294f8dSArtem Dergachev SVal VisitSymSymExpr(const SymSymExpr *S) {
130922746d7dSArtem Dergachev auto I = Cached.find(S);
131022746d7dSArtem Dergachev if (I != Cached.end())
131122746d7dSArtem Dergachev return I->second;
131222746d7dSArtem Dergachev
131305220a90SArtem Dergachev // For now don't try to simplify mixed Loc/NonLoc expressions
131405220a90SArtem Dergachev // because they often appear from LocAsInteger operations
131505220a90SArtem Dergachev // and we don't know how to combine a LocAsInteger
131605220a90SArtem Dergachev // with a concrete value.
131705220a90SArtem Dergachev if (Loc::isLocType(S->getLHS()->getType()) !=
13189fe9a95fSArtem Dergachev Loc::isLocType(S->getRHS()->getType()))
13199fe9a95fSArtem Dergachev return skip(S);
132005220a90SArtem Dergachev
13210a17896fSGabor Marton SVal LHS = getConstOrVisit(S->getLHS());
13220a17896fSGabor Marton SVal RHS = getConstOrVisit(S->getRHS());
13230a17896fSGabor Marton
13249fe9a95fSArtem Dergachev if (isUnchanged(S->getLHS(), LHS) && isUnchanged(S->getRHS(), RHS))
13259fe9a95fSArtem Dergachev return skip(S);
13269fe9a95fSArtem Dergachev
13279fe9a95fSArtem Dergachev return cache(
13289fe9a95fSArtem Dergachev S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
132912294f8dSArtem Dergachev }
133012294f8dSArtem Dergachev
1331160798abSGabor Marton SVal VisitSymbolCast(const SymbolCast *S) {
1332160798abSGabor Marton auto I = Cached.find(S);
1333160798abSGabor Marton if (I != Cached.end())
1334160798abSGabor Marton return I->second;
1335160798abSGabor Marton const SymExpr *OpSym = S->getOperand();
1336160798abSGabor Marton SVal OpVal = getConstOrVisit(OpSym);
1337160798abSGabor Marton if (isUnchanged(OpSym, OpVal))
1338160798abSGabor Marton return skip(S);
1339160798abSGabor Marton
1340160798abSGabor Marton return cache(S, SVB.evalCast(OpVal, S->getType(), OpSym->getType()));
1341160798abSGabor Marton }
1342b5b2aec1SGabor Marton
1343b5b2aec1SGabor Marton SVal VisitUnarySymExpr(const UnarySymExpr *S) {
1344b5b2aec1SGabor Marton auto I = Cached.find(S);
1345b5b2aec1SGabor Marton if (I != Cached.end())
1346b5b2aec1SGabor Marton return I->second;
1347b5b2aec1SGabor Marton SVal Op = getConstOrVisit(S->getOperand());
1348b5b2aec1SGabor Marton if (isUnchanged(S->getOperand(), Op))
1349b5b2aec1SGabor Marton return skip(S);
1350b5b2aec1SGabor Marton
1351b5b2aec1SGabor Marton return cache(
1352b5b2aec1SGabor Marton S, SVB.evalUnaryOp(State, S->getOpcode(), Op, S->getType()));
1353b5b2aec1SGabor Marton }
1354b5b2aec1SGabor Marton
135512294f8dSArtem Dergachev SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); }
135612294f8dSArtem Dergachev
135712294f8dSArtem Dergachev SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); }
135812294f8dSArtem Dergachev
135912294f8dSArtem Dergachev SVal VisitNonLocSymbolVal(nonloc::SymbolVal V) {
136012294f8dSArtem Dergachev // Simplification is much more costly than computing complexity.
136112294f8dSArtem Dergachev // For high complexity, it may be not worth it.
136212294f8dSArtem Dergachev return Visit(V.getSymbol());
136312294f8dSArtem Dergachev }
136412294f8dSArtem Dergachev
136512294f8dSArtem Dergachev SVal VisitSVal(SVal V) { return V; }
136612294f8dSArtem Dergachev };
136712294f8dSArtem Dergachev
136816a1f64cSArtem Dergachev SVal SimplifiedV = Simplifier(State).Visit(V);
136916a1f64cSArtem Dergachev return SimplifiedV;
137012294f8dSArtem Dergachev }
1371