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 {
24fa0734ecSArgyrios Kyrtzidis public:
25fa0734ecSArgyrios Kyrtzidis   SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
26001fd5b4STed Kremenek                     ProgramStateManager &stateMgr)
27fa0734ecSArgyrios Kyrtzidis       : SValBuilder(alloc, context, stateMgr) {}
28637d1e66SAngel Garcia Gomez   ~SimpleSValBuilder() override {}
29fa0734ecSArgyrios Kyrtzidis 
30fb6b25b5SCraig Topper   SVal evalMinus(NonLoc val) override;
31fb6b25b5SCraig Topper   SVal evalComplement(NonLoc val) override;
32fb6b25b5SCraig Topper   SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
33fb6b25b5SCraig Topper                    NonLoc lhs, NonLoc rhs, QualType resultTy) override;
34fb6b25b5SCraig Topper   SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
35fb6b25b5SCraig Topper                    Loc lhs, Loc rhs, QualType resultTy) override;
36fb6b25b5SCraig Topper   SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
37fb6b25b5SCraig Topper                    Loc lhs, NonLoc rhs, QualType resultTy) override;
38fa0734ecSArgyrios Kyrtzidis 
39fa0734ecSArgyrios Kyrtzidis   /// getKnownValue - evaluates a given SVal. If the SVal has only one possible
40fa0734ecSArgyrios Kyrtzidis   ///  (integer) value, that value is returned. Otherwise, returns NULL.
41fb6b25b5SCraig Topper   const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override;
42fa0734ecSArgyrios Kyrtzidis 
4312294f8dSArtem Dergachev   /// Recursively descends into symbolic expressions and replaces symbols
4412294f8dSArtem Dergachev   /// with their known values (in the sense of the getKnownValue() method).
4512294f8dSArtem Dergachev   SVal simplifySVal(ProgramStateRef State, SVal V) override;
4612294f8dSArtem Dergachev 
47fa0734ecSArgyrios Kyrtzidis   SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
48fa0734ecSArgyrios Kyrtzidis                      const llvm::APSInt &RHS, QualType resultTy);
49fa0734ecSArgyrios Kyrtzidis };
50fa0734ecSArgyrios Kyrtzidis } // end anonymous namespace
51fa0734ecSArgyrios Kyrtzidis 
52fa0734ecSArgyrios Kyrtzidis SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
53fa0734ecSArgyrios Kyrtzidis                                            ASTContext &context,
54001fd5b4STed Kremenek                                            ProgramStateManager &stateMgr) {
55fa0734ecSArgyrios Kyrtzidis   return new SimpleSValBuilder(alloc, context, stateMgr);
56fa0734ecSArgyrios Kyrtzidis }
57fa0734ecSArgyrios Kyrtzidis 
58fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
59fa0734ecSArgyrios Kyrtzidis // Transfer function for unary operators.
60fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
61fa0734ecSArgyrios Kyrtzidis 
62fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::evalMinus(NonLoc val) {
63fa0734ecSArgyrios Kyrtzidis   switch (val.getSubKind()) {
64fa0734ecSArgyrios Kyrtzidis   case nonloc::ConcreteIntKind:
652fdacbc5SDavid Blaikie     return val.castAs<nonloc::ConcreteInt>().evalMinus(*this);
66fa0734ecSArgyrios Kyrtzidis   default:
67fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
68fa0734ecSArgyrios Kyrtzidis   }
69fa0734ecSArgyrios Kyrtzidis }
70fa0734ecSArgyrios Kyrtzidis 
71fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::evalComplement(NonLoc X) {
72fa0734ecSArgyrios Kyrtzidis   switch (X.getSubKind()) {
73fa0734ecSArgyrios Kyrtzidis   case nonloc::ConcreteIntKind:
742fdacbc5SDavid Blaikie     return X.castAs<nonloc::ConcreteInt>().evalComplement(*this);
75fa0734ecSArgyrios Kyrtzidis   default:
76fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
77fa0734ecSArgyrios Kyrtzidis   }
78fa0734ecSArgyrios Kyrtzidis }
79fa0734ecSArgyrios Kyrtzidis 
80fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
81fa0734ecSArgyrios Kyrtzidis // Transfer function for binary operators.
82fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
83fa0734ecSArgyrios Kyrtzidis 
84fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
85fa0734ecSArgyrios Kyrtzidis                                     BinaryOperator::Opcode op,
86fa0734ecSArgyrios Kyrtzidis                                     const llvm::APSInt &RHS,
87fa0734ecSArgyrios Kyrtzidis                                     QualType resultTy) {
88fa0734ecSArgyrios Kyrtzidis   bool isIdempotent = false;
89fa0734ecSArgyrios Kyrtzidis 
90fa0734ecSArgyrios Kyrtzidis   // Check for a few special cases with known reductions first.
91fa0734ecSArgyrios Kyrtzidis   switch (op) {
92fa0734ecSArgyrios Kyrtzidis   default:
93fa0734ecSArgyrios Kyrtzidis     // We can't reduce this case; just treat it normally.
94fa0734ecSArgyrios Kyrtzidis     break;
95fa0734ecSArgyrios Kyrtzidis   case BO_Mul:
96fa0734ecSArgyrios Kyrtzidis     // a*0 and a*1
97fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
98fa0734ecSArgyrios Kyrtzidis       return makeIntVal(0, resultTy);
99fa0734ecSArgyrios Kyrtzidis     else if (RHS == 1)
100fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
101fa0734ecSArgyrios Kyrtzidis     break;
102fa0734ecSArgyrios Kyrtzidis   case BO_Div:
103fa0734ecSArgyrios Kyrtzidis     // a/0 and a/1
104fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
105fa0734ecSArgyrios Kyrtzidis       // This is also handled elsewhere.
106fa0734ecSArgyrios Kyrtzidis       return UndefinedVal();
107fa0734ecSArgyrios Kyrtzidis     else if (RHS == 1)
108fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
109fa0734ecSArgyrios Kyrtzidis     break;
110fa0734ecSArgyrios Kyrtzidis   case BO_Rem:
111fa0734ecSArgyrios Kyrtzidis     // a%0 and a%1
112fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
113fa0734ecSArgyrios Kyrtzidis       // This is also handled elsewhere.
114fa0734ecSArgyrios Kyrtzidis       return UndefinedVal();
115fa0734ecSArgyrios Kyrtzidis     else if (RHS == 1)
116fa0734ecSArgyrios Kyrtzidis       return makeIntVal(0, resultTy);
117fa0734ecSArgyrios Kyrtzidis     break;
118fa0734ecSArgyrios Kyrtzidis   case BO_Add:
119fa0734ecSArgyrios Kyrtzidis   case BO_Sub:
120fa0734ecSArgyrios Kyrtzidis   case BO_Shl:
121fa0734ecSArgyrios Kyrtzidis   case BO_Shr:
122fa0734ecSArgyrios Kyrtzidis   case BO_Xor:
123fa0734ecSArgyrios Kyrtzidis     // a+0, a-0, a<<0, a>>0, a^0
124fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
125fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
126fa0734ecSArgyrios Kyrtzidis     break;
127fa0734ecSArgyrios Kyrtzidis   case BO_And:
128fa0734ecSArgyrios Kyrtzidis     // a&0 and a&(~0)
129fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
130fa0734ecSArgyrios Kyrtzidis       return makeIntVal(0, resultTy);
131d933adeaSJay Foad     else if (RHS.isAllOnes())
132fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
133fa0734ecSArgyrios Kyrtzidis     break;
134fa0734ecSArgyrios Kyrtzidis   case BO_Or:
135fa0734ecSArgyrios Kyrtzidis     // a|0 and a|(~0)
136fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
137fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
138d933adeaSJay Foad     else if (RHS.isAllOnes()) {
139fa0734ecSArgyrios Kyrtzidis       const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
140fa0734ecSArgyrios Kyrtzidis       return nonloc::ConcreteInt(Result);
141fa0734ecSArgyrios Kyrtzidis     }
142fa0734ecSArgyrios Kyrtzidis     break;
143fa0734ecSArgyrios Kyrtzidis   }
144fa0734ecSArgyrios Kyrtzidis 
145fa0734ecSArgyrios Kyrtzidis   // Idempotent ops (like a*1) can still change the type of an expression.
14601ddfa95SDenys Petrov   // Wrap the LHS up in a NonLoc again and let evalCast do the
1475ad574c0SZhanyong Wan   // dirty work.
148d066f79cSAnna Zaks   if (isIdempotent)
14901ddfa95SDenys Petrov     return evalCast(nonloc::SymbolVal(LHS), resultTy, QualType{});
150fa0734ecSArgyrios Kyrtzidis 
151fa0734ecSArgyrios Kyrtzidis   // If we reach this point, the expression cannot be simplified.
15254569448SJordy Rose   // Make a SymbolVal for the entire expression, after converting the RHS.
15354569448SJordy Rose   const llvm::APSInt *ConvertedRHS = &RHS;
15454569448SJordy Rose   if (BinaryOperator::isComparisonOp(op)) {
15554569448SJordy Rose     // We're looking for a type big enough to compare the symbolic value
15654569448SJordy Rose     // with the given constant.
15754569448SJordy Rose     // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
15854569448SJordy Rose     ASTContext &Ctx = getContext();
159a808e165STed Kremenek     QualType SymbolType = LHS->getType();
16054569448SJordy Rose     uint64_t ValWidth = RHS.getBitWidth();
16154569448SJordy Rose     uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
16254569448SJordy Rose 
16354569448SJordy Rose     if (ValWidth < TypeWidth) {
16454569448SJordy Rose       // If the value is too small, extend it.
16554569448SJordy Rose       ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
16654569448SJordy Rose     } else if (ValWidth == TypeWidth) {
16754569448SJordy Rose       // If the value is signed but the symbol is unsigned, do the comparison
16854569448SJordy Rose       // in unsigned space. [C99 6.3.1.8]
16954569448SJordy Rose       // (For the opposite case, the value is already unsigned.)
17054569448SJordy Rose       if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
17154569448SJordy Rose         ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
17254569448SJordy Rose     }
17354569448SJordy Rose   } else
17454569448SJordy Rose     ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
17554569448SJordy Rose 
17654569448SJordy Rose   return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
177fa0734ecSArgyrios Kyrtzidis }
178fa0734ecSArgyrios Kyrtzidis 
1792bbccca9SAdam Balogh // See if Sym is known to be a relation Rel with Bound.
1802bbccca9SAdam Balogh static bool isInRelation(BinaryOperator::Opcode Rel, SymbolRef Sym,
1812bbccca9SAdam Balogh                          llvm::APSInt Bound, ProgramStateRef State) {
1822bbccca9SAdam Balogh   SValBuilder &SVB = State->getStateManager().getSValBuilder();
1832bbccca9SAdam Balogh   SVal Result =
1842bbccca9SAdam Balogh       SVB.evalBinOpNN(State, Rel, nonloc::SymbolVal(Sym),
1852bbccca9SAdam Balogh                       nonloc::ConcreteInt(Bound), SVB.getConditionType());
1862bbccca9SAdam Balogh   if (auto DV = Result.getAs<DefinedSVal>()) {
1872bbccca9SAdam Balogh     return !State->assume(*DV, false);
1882bbccca9SAdam Balogh   }
1892bbccca9SAdam Balogh   return false;
1902bbccca9SAdam Balogh }
1912bbccca9SAdam Balogh 
1922bbccca9SAdam Balogh // See if Sym is known to be within [min/4, max/4], where min and max
1932bbccca9SAdam Balogh // are the bounds of the symbol's integral type. With such symbols,
1942bbccca9SAdam Balogh // some manipulations can be performed without the risk of overflow.
1952bbccca9SAdam Balogh // assume() doesn't cause infinite recursion because we should be dealing
1962bbccca9SAdam Balogh // with simpler symbols on every recursive call.
1972bbccca9SAdam Balogh static bool isWithinConstantOverflowBounds(SymbolRef Sym,
1982bbccca9SAdam Balogh                                            ProgramStateRef State) {
1992bbccca9SAdam Balogh   SValBuilder &SVB = State->getStateManager().getSValBuilder();
2002bbccca9SAdam Balogh   BasicValueFactory &BV = SVB.getBasicValueFactory();
2012bbccca9SAdam Balogh 
2022bbccca9SAdam Balogh   QualType T = Sym->getType();
2032bbccca9SAdam Balogh   assert(T->isSignedIntegerOrEnumerationType() &&
2042bbccca9SAdam Balogh          "This only works with signed integers!");
2052bbccca9SAdam Balogh   APSIntType AT = BV.getAPSIntType(T);
2062bbccca9SAdam Balogh 
2072bbccca9SAdam Balogh   llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
2082bbccca9SAdam Balogh   return isInRelation(BO_LE, Sym, Max, State) &&
2092bbccca9SAdam Balogh          isInRelation(BO_GE, Sym, Min, State);
2102bbccca9SAdam Balogh }
2112bbccca9SAdam Balogh 
2122bbccca9SAdam Balogh // Same for the concrete integers: see if I is within [min/4, max/4].
2132bbccca9SAdam Balogh static bool isWithinConstantOverflowBounds(llvm::APSInt I) {
2142bbccca9SAdam Balogh   APSIntType AT(I);
2152bbccca9SAdam Balogh   assert(!AT.isUnsigned() &&
2162bbccca9SAdam Balogh          "This only works with signed integers!");
2172bbccca9SAdam Balogh 
2182bbccca9SAdam Balogh   llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
2192bbccca9SAdam Balogh   return (I <= Max) && (I >= -Max);
2202bbccca9SAdam Balogh }
2212bbccca9SAdam Balogh 
2222bbccca9SAdam Balogh static std::pair<SymbolRef, llvm::APSInt>
2232bbccca9SAdam Balogh decomposeSymbol(SymbolRef Sym, BasicValueFactory &BV) {
2242bbccca9SAdam Balogh   if (const auto *SymInt = dyn_cast<SymIntExpr>(Sym))
2252bbccca9SAdam Balogh     if (BinaryOperator::isAdditiveOp(SymInt->getOpcode()))
2262bbccca9SAdam Balogh       return std::make_pair(SymInt->getLHS(),
2272bbccca9SAdam Balogh                             (SymInt->getOpcode() == BO_Add) ?
2282bbccca9SAdam Balogh                             (SymInt->getRHS()) :
2292bbccca9SAdam Balogh                             (-SymInt->getRHS()));
2302bbccca9SAdam Balogh 
2312bbccca9SAdam Balogh   // Fail to decompose: "reduce" the problem to the "$x + 0" case.
2322bbccca9SAdam Balogh   return std::make_pair(Sym, BV.getValue(0, Sym->getType()));
2332bbccca9SAdam Balogh }
2342bbccca9SAdam Balogh 
2352bbccca9SAdam Balogh // Simplify "(LSym + LInt) Op (RSym + RInt)" assuming all values are of the
2362bbccca9SAdam Balogh // same signed integral type and no overflows occur (which should be checked
2372bbccca9SAdam Balogh // by the caller).
2382bbccca9SAdam Balogh static NonLoc doRearrangeUnchecked(ProgramStateRef State,
2392bbccca9SAdam Balogh                                    BinaryOperator::Opcode Op,
2402bbccca9SAdam Balogh                                    SymbolRef LSym, llvm::APSInt LInt,
2412bbccca9SAdam Balogh                                    SymbolRef RSym, llvm::APSInt RInt) {
2422bbccca9SAdam Balogh   SValBuilder &SVB = State->getStateManager().getSValBuilder();
2432bbccca9SAdam Balogh   BasicValueFactory &BV = SVB.getBasicValueFactory();
2442bbccca9SAdam Balogh   SymbolManager &SymMgr = SVB.getSymbolManager();
2452bbccca9SAdam Balogh 
2462bbccca9SAdam Balogh   QualType SymTy = LSym->getType();
2472bbccca9SAdam Balogh   assert(SymTy == RSym->getType() &&
2482bbccca9SAdam Balogh          "Symbols are not of the same type!");
2492bbccca9SAdam Balogh   assert(APSIntType(LInt) == BV.getAPSIntType(SymTy) &&
2502bbccca9SAdam Balogh          "Integers are not of the same type as symbols!");
2512bbccca9SAdam Balogh   assert(APSIntType(RInt) == BV.getAPSIntType(SymTy) &&
2522bbccca9SAdam Balogh          "Integers are not of the same type as symbols!");
2532bbccca9SAdam Balogh 
2542bbccca9SAdam Balogh   QualType ResultTy;
2552bbccca9SAdam Balogh   if (BinaryOperator::isComparisonOp(Op))
2562bbccca9SAdam Balogh     ResultTy = SVB.getConditionType();
2572bbccca9SAdam Balogh   else if (BinaryOperator::isAdditiveOp(Op))
2582bbccca9SAdam Balogh     ResultTy = SymTy;
2592bbccca9SAdam Balogh   else
2602bbccca9SAdam Balogh     llvm_unreachable("Operation not suitable for unchecked rearrangement!");
2612bbccca9SAdam Balogh 
2622bbccca9SAdam Balogh   // FIXME: Can we use assume() without getting into an infinite recursion?
2632bbccca9SAdam Balogh   if (LSym == RSym)
2642bbccca9SAdam Balogh     return SVB.evalBinOpNN(State, Op, nonloc::ConcreteInt(LInt),
2652bbccca9SAdam Balogh                            nonloc::ConcreteInt(RInt), ResultTy)
2662bbccca9SAdam Balogh         .castAs<NonLoc>();
2672bbccca9SAdam Balogh 
2682bbccca9SAdam Balogh   SymbolRef ResultSym = nullptr;
2692bbccca9SAdam Balogh   BinaryOperator::Opcode ResultOp;
2702bbccca9SAdam Balogh   llvm::APSInt ResultInt;
2712bbccca9SAdam Balogh   if (BinaryOperator::isComparisonOp(Op)) {
2722bbccca9SAdam Balogh     // Prefer comparing to a non-negative number.
2732bbccca9SAdam Balogh     // FIXME: Maybe it'd be better to have consistency in
2742bbccca9SAdam Balogh     // "$x - $y" vs. "$y - $x" because those are solver's keys.
2752bbccca9SAdam Balogh     if (LInt > RInt) {
2762bbccca9SAdam Balogh       ResultSym = SymMgr.getSymSymExpr(RSym, BO_Sub, LSym, SymTy);
2772bbccca9SAdam Balogh       ResultOp = BinaryOperator::reverseComparisonOp(Op);
2782bbccca9SAdam Balogh       ResultInt = LInt - RInt; // Opposite order!
2792bbccca9SAdam Balogh     } else {
2802bbccca9SAdam Balogh       ResultSym = SymMgr.getSymSymExpr(LSym, BO_Sub, RSym, SymTy);
2812bbccca9SAdam Balogh       ResultOp = Op;
2822bbccca9SAdam Balogh       ResultInt = RInt - LInt; // Opposite order!
2832bbccca9SAdam Balogh     }
2842bbccca9SAdam Balogh   } else {
2852bbccca9SAdam Balogh     ResultSym = SymMgr.getSymSymExpr(LSym, Op, RSym, SymTy);
2862bbccca9SAdam Balogh     ResultInt = (Op == BO_Add) ? (LInt + RInt) : (LInt - RInt);
2872bbccca9SAdam Balogh     ResultOp = BO_Add;
2882bbccca9SAdam Balogh     // Bring back the cosmetic difference.
2892bbccca9SAdam Balogh     if (ResultInt < 0) {
2902bbccca9SAdam Balogh       ResultInt = -ResultInt;
2912bbccca9SAdam Balogh       ResultOp = BO_Sub;
2922bbccca9SAdam Balogh     } else if (ResultInt == 0) {
2932bbccca9SAdam Balogh       // Shortcut: Simplify "$x + 0" to "$x".
2942bbccca9SAdam Balogh       return nonloc::SymbolVal(ResultSym);
2952bbccca9SAdam Balogh     }
2962bbccca9SAdam Balogh   }
2972bbccca9SAdam Balogh   const llvm::APSInt &PersistentResultInt = BV.getValue(ResultInt);
2982bbccca9SAdam Balogh   return nonloc::SymbolVal(
2992bbccca9SAdam Balogh       SymMgr.getSymIntExpr(ResultSym, ResultOp, PersistentResultInt, ResultTy));
3002bbccca9SAdam Balogh }
3012bbccca9SAdam Balogh 
3022bbccca9SAdam Balogh // Rearrange if symbol type matches the result type and if the operator is a
3032bbccca9SAdam Balogh // comparison operator, both symbol and constant must be within constant
3042bbccca9SAdam Balogh // overflow bounds.
3052bbccca9SAdam Balogh static bool shouldRearrange(ProgramStateRef State, BinaryOperator::Opcode Op,
3062bbccca9SAdam Balogh                             SymbolRef Sym, llvm::APSInt Int, QualType Ty) {
3072bbccca9SAdam Balogh   return Sym->getType() == Ty &&
3082bbccca9SAdam Balogh     (!BinaryOperator::isComparisonOp(Op) ||
3092bbccca9SAdam Balogh      (isWithinConstantOverflowBounds(Sym, State) &&
3102bbccca9SAdam Balogh       isWithinConstantOverflowBounds(Int)));
3112bbccca9SAdam Balogh }
3122bbccca9SAdam Balogh 
3132bbccca9SAdam Balogh static Optional<NonLoc> tryRearrange(ProgramStateRef State,
3142bbccca9SAdam Balogh                                      BinaryOperator::Opcode Op, NonLoc Lhs,
3152bbccca9SAdam Balogh                                      NonLoc Rhs, QualType ResultTy) {
3162bbccca9SAdam Balogh   ProgramStateManager &StateMgr = State->getStateManager();
3172bbccca9SAdam Balogh   SValBuilder &SVB = StateMgr.getSValBuilder();
3182bbccca9SAdam Balogh 
3192bbccca9SAdam Balogh   // We expect everything to be of the same type - this type.
3202bbccca9SAdam Balogh   QualType SingleTy;
3212bbccca9SAdam Balogh 
322dcde8accSAdam Balogh   // FIXME: After putting complexity threshold to the symbols we can always
323dcde8accSAdam Balogh   //        rearrange additive operations but rearrange comparisons only if
324dcde8accSAdam Balogh   //        option is set.
325b97a9640SBalazs Benics   if (!SVB.getAnalyzerOptions().ShouldAggressivelySimplifyBinaryOperation)
326dcde8accSAdam Balogh     return None;
327dcde8accSAdam Balogh 
3282bbccca9SAdam Balogh   SymbolRef LSym = Lhs.getAsSymbol();
3292bbccca9SAdam Balogh   if (!LSym)
3302bbccca9SAdam Balogh     return None;
3312bbccca9SAdam Balogh 
332dcde8accSAdam Balogh   if (BinaryOperator::isComparisonOp(Op)) {
3332bbccca9SAdam Balogh     SingleTy = LSym->getType();
3342bbccca9SAdam Balogh     if (ResultTy != SVB.getConditionType())
3352bbccca9SAdam Balogh       return None;
3362bbccca9SAdam Balogh     // Initialize SingleTy later with a symbol's type.
3372bbccca9SAdam Balogh   } else if (BinaryOperator::isAdditiveOp(Op)) {
3382bbccca9SAdam Balogh     SingleTy = ResultTy;
33913e186c0SAdam Balogh     if (LSym->getType() != SingleTy)
34013e186c0SAdam Balogh       return None;
3412bbccca9SAdam Balogh   } else {
3422bbccca9SAdam Balogh     // Don't rearrange other operations.
3432bbccca9SAdam Balogh     return None;
3442bbccca9SAdam Balogh   }
3452bbccca9SAdam Balogh 
3462bbccca9SAdam Balogh   assert(!SingleTy.isNull() && "We should have figured out the type by now!");
3472bbccca9SAdam Balogh 
348471d0864SAdam Balogh   // Rearrange signed symbolic expressions only
349471d0864SAdam Balogh   if (!SingleTy->isSignedIntegerOrEnumerationType())
350471d0864SAdam Balogh     return None;
351471d0864SAdam Balogh 
3522bbccca9SAdam Balogh   SymbolRef RSym = Rhs.getAsSymbol();
3532bbccca9SAdam Balogh   if (!RSym || RSym->getType() != SingleTy)
3542bbccca9SAdam Balogh     return None;
3552bbccca9SAdam Balogh 
3562bbccca9SAdam Balogh   BasicValueFactory &BV = State->getBasicVals();
3572bbccca9SAdam Balogh   llvm::APSInt LInt, RInt;
3582bbccca9SAdam Balogh   std::tie(LSym, LInt) = decomposeSymbol(LSym, BV);
3592bbccca9SAdam Balogh   std::tie(RSym, RInt) = decomposeSymbol(RSym, BV);
3602bbccca9SAdam Balogh   if (!shouldRearrange(State, Op, LSym, LInt, SingleTy) ||
3612bbccca9SAdam Balogh       !shouldRearrange(State, Op, RSym, RInt, SingleTy))
3622bbccca9SAdam Balogh     return None;
3632bbccca9SAdam Balogh 
3642bbccca9SAdam Balogh   // We know that no overflows can occur anymore.
3652bbccca9SAdam Balogh   return doRearrangeUnchecked(State, Op, LSym, LInt, RSym, RInt);
3662bbccca9SAdam Balogh }
3672bbccca9SAdam Balogh 
36849b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
369fa0734ecSArgyrios Kyrtzidis                                   BinaryOperator::Opcode op,
370fa0734ecSArgyrios Kyrtzidis                                   NonLoc lhs, NonLoc rhs,
371fa0734ecSArgyrios Kyrtzidis                                   QualType resultTy)  {
372f0e9ca86SAnna Zaks   NonLoc InputLHS = lhs;
373f0e9ca86SAnna Zaks   NonLoc InputRHS = rhs;
374f0e9ca86SAnna Zaks 
375fa0734ecSArgyrios Kyrtzidis   // Handle trivial case where left-side and right-side are the same.
376fa0734ecSArgyrios Kyrtzidis   if (lhs == rhs)
377fa0734ecSArgyrios Kyrtzidis     switch (op) {
378fa0734ecSArgyrios Kyrtzidis       default:
379fa0734ecSArgyrios Kyrtzidis         break;
380fa0734ecSArgyrios Kyrtzidis       case BO_EQ:
381fa0734ecSArgyrios Kyrtzidis       case BO_LE:
382fa0734ecSArgyrios Kyrtzidis       case BO_GE:
383fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(true, resultTy);
384fa0734ecSArgyrios Kyrtzidis       case BO_LT:
385fa0734ecSArgyrios Kyrtzidis       case BO_GT:
386fa0734ecSArgyrios Kyrtzidis       case BO_NE:
387fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(false, resultTy);
388fa0734ecSArgyrios Kyrtzidis       case BO_Xor:
389fa0734ecSArgyrios Kyrtzidis       case BO_Sub:
3907523d1a8SJordan Rose         if (resultTy->isIntegralOrEnumerationType())
391fa0734ecSArgyrios Kyrtzidis           return makeIntVal(0, resultTy);
39201ddfa95SDenys Petrov         return evalCast(makeIntVal(0, /*isUnsigned=*/false), resultTy,
39301ddfa95SDenys Petrov                         QualType{});
394fa0734ecSArgyrios Kyrtzidis       case BO_Or:
395fa0734ecSArgyrios Kyrtzidis       case BO_And:
39601ddfa95SDenys Petrov         return evalCast(lhs, resultTy, QualType{});
397fa0734ecSArgyrios Kyrtzidis     }
398fa0734ecSArgyrios Kyrtzidis 
399fa0734ecSArgyrios Kyrtzidis   while (1) {
400fa0734ecSArgyrios Kyrtzidis     switch (lhs.getSubKind()) {
401fa0734ecSArgyrios Kyrtzidis     default:
402bd3e5dbfSGeorge Karpenkov       return makeSymExprValNN(op, lhs, rhs, resultTy);
40364c01f7bSDevin Coughlin     case nonloc::PointerToMemberKind: {
40464c01f7bSDevin Coughlin       assert(rhs.getSubKind() == nonloc::PointerToMemberKind &&
40564c01f7bSDevin Coughlin              "Both SVals should have pointer-to-member-type");
40664c01f7bSDevin Coughlin       auto LPTM = lhs.castAs<nonloc::PointerToMember>(),
40764c01f7bSDevin Coughlin            RPTM = rhs.castAs<nonloc::PointerToMember>();
40864c01f7bSDevin Coughlin       auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData();
40964c01f7bSDevin Coughlin       switch (op) {
41064c01f7bSDevin Coughlin         case BO_EQ:
41164c01f7bSDevin Coughlin           return makeTruthVal(LPTMD == RPTMD, resultTy);
41264c01f7bSDevin Coughlin         case BO_NE:
41364c01f7bSDevin Coughlin           return makeTruthVal(LPTMD != RPTMD, resultTy);
41464c01f7bSDevin Coughlin         default:
41564c01f7bSDevin Coughlin           return UnknownVal();
41664c01f7bSDevin Coughlin       }
41764c01f7bSDevin Coughlin     }
418fa0734ecSArgyrios Kyrtzidis     case nonloc::LocAsIntegerKind: {
4192fdacbc5SDavid Blaikie       Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc();
420fa0734ecSArgyrios Kyrtzidis       switch (rhs.getSubKind()) {
421fa0734ecSArgyrios Kyrtzidis         case nonloc::LocAsIntegerKind:
42218d77984SAlexander Shaposhnikov           // FIXME: at the moment the implementation
42318d77984SAlexander Shaposhnikov           // of modeling "pointers as integers" is not complete.
42418d77984SAlexander Shaposhnikov           if (!BinaryOperator::isComparisonOp(op))
42518d77984SAlexander Shaposhnikov             return UnknownVal();
426fa0734ecSArgyrios Kyrtzidis           return evalBinOpLL(state, op, lhsL,
4272fdacbc5SDavid Blaikie                              rhs.castAs<nonloc::LocAsInteger>().getLoc(),
428fa0734ecSArgyrios Kyrtzidis                              resultTy);
429fa0734ecSArgyrios Kyrtzidis         case nonloc::ConcreteIntKind: {
43018d77984SAlexander Shaposhnikov           // FIXME: at the moment the implementation
43118d77984SAlexander Shaposhnikov           // of modeling "pointers as integers" is not complete.
43218d77984SAlexander Shaposhnikov           if (!BinaryOperator::isComparisonOp(op))
43318d77984SAlexander Shaposhnikov             return UnknownVal();
434fa0734ecSArgyrios Kyrtzidis           // Transform the integer into a location and compare.
4357333a9eaSArtem Dergachev           // FIXME: This only makes sense for comparisons. If we want to, say,
4367333a9eaSArtem Dergachev           // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it,
4377333a9eaSArtem Dergachev           // then pack it back into a LocAsInteger.
4382fdacbc5SDavid Blaikie           llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue();
43927ed855aSDavid Stenberg           // If the region has a symbolic base, pay attention to the type; it
44027ed855aSDavid Stenberg           // might be coming from a non-default address space. For non-symbolic
44127ed855aSDavid Stenberg           // regions it doesn't matter that much because such comparisons would
44227ed855aSDavid Stenberg           // most likely evaluate to concrete false anyway. FIXME: We might
44327ed855aSDavid Stenberg           // still need to handle the non-comparison case.
44427ed855aSDavid Stenberg           if (SymbolRef lSym = lhs.getAsLocSymbol(true))
44527ed855aSDavid Stenberg             BasicVals.getAPSIntType(lSym->getType()).apply(i);
44627ed855aSDavid Stenberg           else
4477e3c3ea3SJordy Rose             BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
448fa0734ecSArgyrios Kyrtzidis           return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
449fa0734ecSArgyrios Kyrtzidis         }
450fa0734ecSArgyrios Kyrtzidis         default:
451fa0734ecSArgyrios Kyrtzidis           switch (op) {
452fa0734ecSArgyrios Kyrtzidis             case BO_EQ:
453fa0734ecSArgyrios Kyrtzidis               return makeTruthVal(false, resultTy);
454fa0734ecSArgyrios Kyrtzidis             case BO_NE:
455fa0734ecSArgyrios Kyrtzidis               return makeTruthVal(true, resultTy);
456fa0734ecSArgyrios Kyrtzidis             default:
457fa0734ecSArgyrios Kyrtzidis               // This case also handles pointer arithmetic.
458bd3e5dbfSGeorge Karpenkov               return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
459fa0734ecSArgyrios Kyrtzidis           }
460fa0734ecSArgyrios Kyrtzidis       }
461fa0734ecSArgyrios Kyrtzidis     }
462d066f79cSAnna Zaks     case nonloc::ConcreteIntKind: {
4632fdacbc5SDavid Blaikie       llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
464d066f79cSAnna Zaks 
46554569448SJordy Rose       // If we're dealing with two known constants, just perform the operation.
46654569448SJordy Rose       if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) {
46754569448SJordy Rose         llvm::APSInt RHSValue = *KnownRHSValue;
46854569448SJordy Rose         if (BinaryOperator::isComparisonOp(op)) {
46954569448SJordy Rose           // We're looking for a type big enough to compare the two values.
4707e3c3ea3SJordy Rose           // FIXME: This is not correct. char + short will result in a promotion
4717e3c3ea3SJordy Rose           // to int. Unfortunately we have lost types by this point.
4727e3c3ea3SJordy Rose           APSIntType CompareType = std::max(APSIntType(LHSValue),
4737e3c3ea3SJordy Rose                                             APSIntType(RHSValue));
4747e3c3ea3SJordy Rose           CompareType.apply(LHSValue);
4757e3c3ea3SJordy Rose           CompareType.apply(RHSValue);
47654569448SJordy Rose         } else if (!BinaryOperator::isShiftOp(op)) {
4777e3c3ea3SJordy Rose           APSIntType IntType = BasicVals.getAPSIntType(resultTy);
4787e3c3ea3SJordy Rose           IntType.apply(LHSValue);
4797e3c3ea3SJordy Rose           IntType.apply(RHSValue);
480d066f79cSAnna Zaks         }
481d066f79cSAnna Zaks 
48254569448SJordy Rose         const llvm::APSInt *Result =
48354569448SJordy Rose           BasicVals.evalAPSInt(op, LHSValue, RHSValue);
48454569448SJordy Rose         if (!Result)
48554569448SJordy Rose           return UndefinedVal();
48654569448SJordy Rose 
48754569448SJordy Rose         return nonloc::ConcreteInt(*Result);
48854569448SJordy Rose       }
489d066f79cSAnna Zaks 
490d066f79cSAnna Zaks       // Swap the left and right sides and flip the operator if doing so
491d066f79cSAnna Zaks       // allows us to better reason about the expression (this is a form
492d066f79cSAnna Zaks       // of expression canonicalization).
493d066f79cSAnna Zaks       // While we're at it, catch some special cases for non-commutative ops.
494d066f79cSAnna Zaks       switch (op) {
495d066f79cSAnna Zaks       case BO_LT:
496d066f79cSAnna Zaks       case BO_GT:
497d066f79cSAnna Zaks       case BO_LE:
498d066f79cSAnna Zaks       case BO_GE:
499604d0bbbSJordan Rose         op = BinaryOperator::reverseComparisonOp(op);
5004dc0b1acSReid Kleckner         LLVM_FALLTHROUGH;
501d066f79cSAnna Zaks       case BO_EQ:
502d066f79cSAnna Zaks       case BO_NE:
503d066f79cSAnna Zaks       case BO_Add:
504d066f79cSAnna Zaks       case BO_Mul:
505d066f79cSAnna Zaks       case BO_And:
506d066f79cSAnna Zaks       case BO_Xor:
507d066f79cSAnna Zaks       case BO_Or:
50854569448SJordy Rose         std::swap(lhs, rhs);
509d066f79cSAnna Zaks         continue;
510d066f79cSAnna Zaks       case BO_Shr:
51154569448SJordy Rose         // (~0)>>a
512d933adeaSJay Foad         if (LHSValue.isAllOnes() && LHSValue.isSigned())
51301ddfa95SDenys Petrov           return evalCast(lhs, resultTy, QualType{});
5144dc0b1acSReid Kleckner         LLVM_FALLTHROUGH;
515d066f79cSAnna Zaks       case BO_Shl:
51654569448SJordy Rose         // 0<<a and 0>>a
51754569448SJordy Rose         if (LHSValue == 0)
51801ddfa95SDenys Petrov           return evalCast(lhs, resultTy, QualType{});
519bd3e5dbfSGeorge Karpenkov         return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
520015c3988SGabor Marton       case BO_Div:
521015c3988SGabor Marton         // 0 / x == 0
52273c120a9SValeriy Savchenko       case BO_Rem:
52373c120a9SValeriy Savchenko         // 0 % x == 0
52473c120a9SValeriy Savchenko         if (LHSValue == 0)
52573c120a9SValeriy Savchenko           return makeZeroVal(resultTy);
52673c120a9SValeriy Savchenko         LLVM_FALLTHROUGH;
527d066f79cSAnna Zaks       default:
528bd3e5dbfSGeorge Karpenkov         return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
529d066f79cSAnna Zaks       }
530d066f79cSAnna Zaks     }
531d066f79cSAnna Zaks     case nonloc::SymbolValKind: {
53254569448SJordy Rose       // We only handle LHS as simple symbols or SymIntExprs.
5332fdacbc5SDavid Blaikie       SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
534d066f79cSAnna Zaks 
535d066f79cSAnna Zaks       // LHS is a symbolic expression.
53654569448SJordy Rose       if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
537fa0734ecSArgyrios Kyrtzidis 
538fa0734ecSArgyrios Kyrtzidis         // Is this a logical not? (!x is represented as x == 0.)
539fa0734ecSArgyrios Kyrtzidis         if (op == BO_EQ && rhs.isZeroConstant()) {
540fa0734ecSArgyrios Kyrtzidis           // We know how to negate certain expressions. Simplify them here.
541fa0734ecSArgyrios Kyrtzidis 
542fa0734ecSArgyrios Kyrtzidis           BinaryOperator::Opcode opc = symIntExpr->getOpcode();
543fa0734ecSArgyrios Kyrtzidis           switch (opc) {
544fa0734ecSArgyrios Kyrtzidis           default:
545fa0734ecSArgyrios Kyrtzidis             // We don't know how to negate this operation.
546fa0734ecSArgyrios Kyrtzidis             // Just handle it as if it were a normal comparison to 0.
547fa0734ecSArgyrios Kyrtzidis             break;
548fa0734ecSArgyrios Kyrtzidis           case BO_LAnd:
549fa0734ecSArgyrios Kyrtzidis           case BO_LOr:
55083d382b1SDavid Blaikie             llvm_unreachable("Logical operators handled by branching logic.");
551fa0734ecSArgyrios Kyrtzidis           case BO_Assign:
552fa0734ecSArgyrios Kyrtzidis           case BO_MulAssign:
553fa0734ecSArgyrios Kyrtzidis           case BO_DivAssign:
554fa0734ecSArgyrios Kyrtzidis           case BO_RemAssign:
555fa0734ecSArgyrios Kyrtzidis           case BO_AddAssign:
556fa0734ecSArgyrios Kyrtzidis           case BO_SubAssign:
557fa0734ecSArgyrios Kyrtzidis           case BO_ShlAssign:
558fa0734ecSArgyrios Kyrtzidis           case BO_ShrAssign:
559fa0734ecSArgyrios Kyrtzidis           case BO_AndAssign:
560fa0734ecSArgyrios Kyrtzidis           case BO_XorAssign:
561fa0734ecSArgyrios Kyrtzidis           case BO_OrAssign:
562fa0734ecSArgyrios Kyrtzidis           case BO_Comma:
56383d382b1SDavid Blaikie             llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
564fa0734ecSArgyrios Kyrtzidis           case BO_PtrMemD:
565fa0734ecSArgyrios Kyrtzidis           case BO_PtrMemI:
56683d382b1SDavid Blaikie             llvm_unreachable("Pointer arithmetic not handled here.");
567fa0734ecSArgyrios Kyrtzidis           case BO_LT:
568fa0734ecSArgyrios Kyrtzidis           case BO_GT:
569fa0734ecSArgyrios Kyrtzidis           case BO_LE:
570fa0734ecSArgyrios Kyrtzidis           case BO_GE:
571fa0734ecSArgyrios Kyrtzidis           case BO_EQ:
572fa0734ecSArgyrios Kyrtzidis           case BO_NE:
573dc16628cSJordan Rose             assert(resultTy->isBooleanType() ||
574dc16628cSJordan Rose                    resultTy == getConditionType());
575dc16628cSJordan Rose             assert(symIntExpr->getType()->isBooleanType() ||
576dc16628cSJordan Rose                    getContext().hasSameUnqualifiedType(symIntExpr->getType(),
577dc16628cSJordan Rose                                                        getConditionType()));
578fa0734ecSArgyrios Kyrtzidis             // Negate the comparison and make a value.
579604d0bbbSJordan Rose             opc = BinaryOperator::negateComparisonOp(opc);
580fa0734ecSArgyrios Kyrtzidis             return makeNonLoc(symIntExpr->getLHS(), opc,
581fa0734ecSArgyrios Kyrtzidis                 symIntExpr->getRHS(), resultTy);
582fa0734ecSArgyrios Kyrtzidis           }
583fa0734ecSArgyrios Kyrtzidis         }
584fa0734ecSArgyrios Kyrtzidis 
585fa0734ecSArgyrios Kyrtzidis         // For now, only handle expressions whose RHS is a constant.
58654569448SJordy Rose         if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) {
587fa0734ecSArgyrios Kyrtzidis           // If both the LHS and the current expression are additive,
58854569448SJordy Rose           // fold their constants and try again.
589fa0734ecSArgyrios Kyrtzidis           if (BinaryOperator::isAdditiveOp(op)) {
590fa0734ecSArgyrios Kyrtzidis             BinaryOperator::Opcode lop = symIntExpr->getOpcode();
591fa0734ecSArgyrios Kyrtzidis             if (BinaryOperator::isAdditiveOp(lop)) {
59254569448SJordy Rose               // Convert the two constants to a common type, then combine them.
59354569448SJordy Rose 
594fa0734ecSArgyrios Kyrtzidis               // resultTy may not be the best type to convert to, but it's
595fa0734ecSArgyrios Kyrtzidis               // probably the best choice in expressions with mixed type
596fa0734ecSArgyrios Kyrtzidis               // (such as x+1U+2LL). The rules for implicit conversions should
597fa0734ecSArgyrios Kyrtzidis               // choose a reasonable type to preserve the expression, and will
598fa0734ecSArgyrios Kyrtzidis               // at least match how the value is going to be used.
5997e3c3ea3SJordy Rose               APSIntType IntType = BasicVals.getAPSIntType(resultTy);
6007e3c3ea3SJordy Rose               const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
6017e3c3ea3SJordy Rose               const llvm::APSInt &second = IntType.convert(*RHSValue);
60254569448SJordy Rose 
603fa0734ecSArgyrios Kyrtzidis               const llvm::APSInt *newRHS;
604fa0734ecSArgyrios Kyrtzidis               if (lop == op)
605fa0734ecSArgyrios Kyrtzidis                 newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
606fa0734ecSArgyrios Kyrtzidis               else
607fa0734ecSArgyrios Kyrtzidis                 newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
60854569448SJordy Rose 
60954569448SJordy Rose               assert(newRHS && "Invalid operation despite common type!");
61054569448SJordy Rose               rhs = nonloc::ConcreteInt(*newRHS);
61154569448SJordy Rose               lhs = nonloc::SymbolVal(symIntExpr->getLHS());
61254569448SJordy Rose               op = lop;
61354569448SJordy Rose               continue;
614fa0734ecSArgyrios Kyrtzidis             }
615fa0734ecSArgyrios Kyrtzidis           }
616fa0734ecSArgyrios Kyrtzidis 
61754569448SJordy Rose           // Otherwise, make a SymIntExpr out of the expression.
61854569448SJordy Rose           return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
61954569448SJordy Rose         }
6203b4c3ea2SJordan Rose       }
621fa0734ecSArgyrios Kyrtzidis 
6223b4c3ea2SJordan Rose       // Does the symbolic expression simplify to a constant?
6233b4c3ea2SJordan Rose       // If so, "fold" the constant by setting 'lhs' to a ConcreteInt
6243b4c3ea2SJordan Rose       // and try again.
62512294f8dSArtem Dergachev       SVal simplifiedLhs = simplifySVal(state, lhs);
62612294f8dSArtem Dergachev       if (simplifiedLhs != lhs)
62712294f8dSArtem Dergachev         if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>()) {
62812294f8dSArtem Dergachev           lhs = *simplifiedLhsAsNonLoc;
629fa0734ecSArgyrios Kyrtzidis           continue;
630fa0734ecSArgyrios Kyrtzidis         }
631fa0734ecSArgyrios Kyrtzidis 
63254569448SJordy Rose       // Is the RHS a constant?
63354569448SJordy Rose       if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
63454569448SJordy Rose         return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
635fa0734ecSArgyrios Kyrtzidis 
6362bbccca9SAdam Balogh       if (Optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy))
6372bbccca9SAdam Balogh         return *V;
6382bbccca9SAdam Balogh 
63954569448SJordy Rose       // Give up -- this is not a symbolic expression we can handle.
640bd3e5dbfSGeorge Karpenkov       return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
641fa0734ecSArgyrios Kyrtzidis     }
642fa0734ecSArgyrios Kyrtzidis     }
643fa0734ecSArgyrios Kyrtzidis   }
644fa0734ecSArgyrios Kyrtzidis }
645fa0734ecSArgyrios Kyrtzidis 
646bac964e1SAnna Zaks static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR,
647bac964e1SAnna Zaks                                             const FieldRegion *RightFR,
648bac964e1SAnna Zaks                                             BinaryOperator::Opcode op,
649bac964e1SAnna Zaks                                             QualType resultTy,
650bac964e1SAnna Zaks                                             SimpleSValBuilder &SVB) {
651bac964e1SAnna Zaks   // Only comparisons are meaningful here!
652bac964e1SAnna Zaks   if (!BinaryOperator::isComparisonOp(op))
653bac964e1SAnna Zaks     return UnknownVal();
654bac964e1SAnna Zaks 
655bac964e1SAnna Zaks   // Next, see if the two FRs have the same super-region.
656bac964e1SAnna Zaks   // FIXME: This doesn't handle casts yet, and simply stripping the casts
657bac964e1SAnna Zaks   // doesn't help.
658bac964e1SAnna Zaks   if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
659bac964e1SAnna Zaks     return UnknownVal();
660bac964e1SAnna Zaks 
661bac964e1SAnna Zaks   const FieldDecl *LeftFD = LeftFR->getDecl();
662bac964e1SAnna Zaks   const FieldDecl *RightFD = RightFR->getDecl();
663bac964e1SAnna Zaks   const RecordDecl *RD = LeftFD->getParent();
664bac964e1SAnna Zaks 
665bac964e1SAnna Zaks   // Make sure the two FRs are from the same kind of record. Just in case!
666bac964e1SAnna Zaks   // FIXME: This is probably where inheritance would be a problem.
667bac964e1SAnna Zaks   if (RD != RightFD->getParent())
668bac964e1SAnna Zaks     return UnknownVal();
669bac964e1SAnna Zaks 
670bac964e1SAnna Zaks   // We know for sure that the two fields are not the same, since that
671bac964e1SAnna Zaks   // would have given us the same SVal.
672bac964e1SAnna Zaks   if (op == BO_EQ)
673bac964e1SAnna Zaks     return SVB.makeTruthVal(false, resultTy);
674bac964e1SAnna Zaks   if (op == BO_NE)
675bac964e1SAnna Zaks     return SVB.makeTruthVal(true, resultTy);
676bac964e1SAnna Zaks 
677bac964e1SAnna Zaks   // Iterate through the fields and see which one comes first.
678bac964e1SAnna Zaks   // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
679bac964e1SAnna Zaks   // members and the units in which bit-fields reside have addresses that
680bac964e1SAnna Zaks   // increase in the order in which they are declared."
681bac964e1SAnna Zaks   bool leftFirst = (op == BO_LT || op == BO_LE);
682e8a8baefSAaron Ballman   for (const auto *I : RD->fields()) {
683e8a8baefSAaron Ballman     if (I == LeftFD)
684bac964e1SAnna Zaks       return SVB.makeTruthVal(leftFirst, resultTy);
685e8a8baefSAaron Ballman     if (I == RightFD)
686bac964e1SAnna Zaks       return SVB.makeTruthVal(!leftFirst, resultTy);
687bac964e1SAnna Zaks   }
688bac964e1SAnna Zaks 
689bac964e1SAnna Zaks   llvm_unreachable("Fields not found in parent record's definition");
690bac964e1SAnna Zaks }
691bac964e1SAnna Zaks 
692fa0734ecSArgyrios Kyrtzidis // FIXME: all this logic will change if/when we have MemRegion::getLocation().
69349b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
694fa0734ecSArgyrios Kyrtzidis                                   BinaryOperator::Opcode op,
695fa0734ecSArgyrios Kyrtzidis                                   Loc lhs, Loc rhs,
696fa0734ecSArgyrios Kyrtzidis                                   QualType resultTy) {
697fa0734ecSArgyrios Kyrtzidis   // Only comparisons and subtractions are valid operations on two pointers.
698fa0734ecSArgyrios Kyrtzidis   // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
699fa0734ecSArgyrios Kyrtzidis   // However, if a pointer is casted to an integer, evalBinOpNN may end up
700fa0734ecSArgyrios Kyrtzidis   // calling this function with another operation (PR7527). We don't attempt to
701fa0734ecSArgyrios Kyrtzidis   // model this for now, but it could be useful, particularly when the
702fa0734ecSArgyrios Kyrtzidis   // "location" is actually an integer value that's been passed through a void*.
703fa0734ecSArgyrios Kyrtzidis   if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
704fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
705fa0734ecSArgyrios Kyrtzidis 
706fa0734ecSArgyrios Kyrtzidis   // Special cases for when both sides are identical.
707fa0734ecSArgyrios Kyrtzidis   if (lhs == rhs) {
708fa0734ecSArgyrios Kyrtzidis     switch (op) {
709fa0734ecSArgyrios Kyrtzidis     default:
71083d382b1SDavid Blaikie       llvm_unreachable("Unimplemented operation for two identical values");
711fa0734ecSArgyrios Kyrtzidis     case BO_Sub:
712fa0734ecSArgyrios Kyrtzidis       return makeZeroVal(resultTy);
713fa0734ecSArgyrios Kyrtzidis     case BO_EQ:
714fa0734ecSArgyrios Kyrtzidis     case BO_LE:
715fa0734ecSArgyrios Kyrtzidis     case BO_GE:
716fa0734ecSArgyrios Kyrtzidis       return makeTruthVal(true, resultTy);
717fa0734ecSArgyrios Kyrtzidis     case BO_NE:
718fa0734ecSArgyrios Kyrtzidis     case BO_LT:
719fa0734ecSArgyrios Kyrtzidis     case BO_GT:
720fa0734ecSArgyrios Kyrtzidis       return makeTruthVal(false, resultTy);
721fa0734ecSArgyrios Kyrtzidis     }
722fa0734ecSArgyrios Kyrtzidis   }
723fa0734ecSArgyrios Kyrtzidis 
724fa0734ecSArgyrios Kyrtzidis   switch (lhs.getSubKind()) {
725fa0734ecSArgyrios Kyrtzidis   default:
72683d382b1SDavid Blaikie     llvm_unreachable("Ordering not implemented for this Loc.");
727fa0734ecSArgyrios Kyrtzidis 
728fa0734ecSArgyrios Kyrtzidis   case loc::GotoLabelKind:
729fa0734ecSArgyrios Kyrtzidis     // The only thing we know about labels is that they're non-null.
730fa0734ecSArgyrios Kyrtzidis     if (rhs.isZeroConstant()) {
731fa0734ecSArgyrios Kyrtzidis       switch (op) {
732fa0734ecSArgyrios Kyrtzidis       default:
733fa0734ecSArgyrios Kyrtzidis         break;
734fa0734ecSArgyrios Kyrtzidis       case BO_Sub:
73501ddfa95SDenys Petrov         return evalCast(lhs, resultTy, QualType{});
736fa0734ecSArgyrios Kyrtzidis       case BO_EQ:
737fa0734ecSArgyrios Kyrtzidis       case BO_LE:
738fa0734ecSArgyrios Kyrtzidis       case BO_LT:
739fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(false, resultTy);
740fa0734ecSArgyrios Kyrtzidis       case BO_NE:
741fa0734ecSArgyrios Kyrtzidis       case BO_GT:
742fa0734ecSArgyrios Kyrtzidis       case BO_GE:
743fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(true, resultTy);
744fa0734ecSArgyrios Kyrtzidis       }
745fa0734ecSArgyrios Kyrtzidis     }
746fa0734ecSArgyrios Kyrtzidis     // There may be two labels for the same location, and a function region may
747fa0734ecSArgyrios Kyrtzidis     // have the same address as a label at the start of the function (depending
748fa0734ecSArgyrios Kyrtzidis     // on the ABI).
749fa0734ecSArgyrios Kyrtzidis     // FIXME: we can probably do a comparison against other MemRegions, though.
750fa0734ecSArgyrios Kyrtzidis     // FIXME: is there a way to tell if two labels refer to the same location?
751fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
752fa0734ecSArgyrios Kyrtzidis 
753fa0734ecSArgyrios Kyrtzidis   case loc::ConcreteIntKind: {
754fa0734ecSArgyrios Kyrtzidis     // If one of the operands is a symbol and the other is a constant,
755fa0734ecSArgyrios Kyrtzidis     // build an expression for use by the constraint manager.
756fa0734ecSArgyrios Kyrtzidis     if (SymbolRef rSym = rhs.getAsLocSymbol()) {
757c0402c69SDominic Chen       // We can only build expressions with symbols on the left,
758c0402c69SDominic Chen       // so we need a reversible operator.
759c70f1d63SRichard Smith       if (!BinaryOperator::isComparisonOp(op) || op == BO_Cmp)
760c0402c69SDominic Chen         return UnknownVal();
76135610d21SDominic Chen 
762c0402c69SDominic Chen       const llvm::APSInt &lVal = lhs.castAs<loc::ConcreteInt>().getValue();
763604d0bbbSJordan Rose       op = BinaryOperator::reverseComparisonOp(op);
764604d0bbbSJordan Rose       return makeNonLoc(rSym, op, lVal, resultTy);
765fa0734ecSArgyrios Kyrtzidis     }
766fa0734ecSArgyrios Kyrtzidis 
767fa0734ecSArgyrios Kyrtzidis     // If both operands are constants, just perform the operation.
76805785d16SDavid Blaikie     if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
7692fdacbc5SDavid Blaikie       SVal ResultVal =
7702fdacbc5SDavid Blaikie           lhs.castAs<loc::ConcreteInt>().evalBinOp(BasicVals, op, *rInt);
7718eca04b2SJordan Rose       if (Optional<NonLoc> Result = ResultVal.getAs<NonLoc>())
77201ddfa95SDenys Petrov         return evalCast(*Result, resultTy, QualType{});
7738eca04b2SJordan Rose 
7748eca04b2SJordan Rose       assert(!ResultVal.getAs<Loc>() && "Loc-Loc ops should not produce Locs");
775fa0734ecSArgyrios Kyrtzidis       return UnknownVal();
776fa0734ecSArgyrios Kyrtzidis     }
777fa0734ecSArgyrios Kyrtzidis 
778fa0734ecSArgyrios Kyrtzidis     // Special case comparisons against NULL.
779fa0734ecSArgyrios Kyrtzidis     // This must come after the test if the RHS is a symbol, which is used to
780fa0734ecSArgyrios Kyrtzidis     // build constraints. The address of any non-symbolic region is guaranteed
781fa0734ecSArgyrios Kyrtzidis     // to be non-NULL, as is any label.
7822fdacbc5SDavid Blaikie     assert(rhs.getAs<loc::MemRegionVal>() || rhs.getAs<loc::GotoLabel>());
783fa0734ecSArgyrios Kyrtzidis     if (lhs.isZeroConstant()) {
784fa0734ecSArgyrios Kyrtzidis       switch (op) {
785fa0734ecSArgyrios Kyrtzidis       default:
786fa0734ecSArgyrios Kyrtzidis         break;
787fa0734ecSArgyrios Kyrtzidis       case BO_EQ:
788fa0734ecSArgyrios Kyrtzidis       case BO_GT:
789fa0734ecSArgyrios Kyrtzidis       case BO_GE:
790fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(false, resultTy);
791fa0734ecSArgyrios Kyrtzidis       case BO_NE:
792fa0734ecSArgyrios Kyrtzidis       case BO_LT:
793fa0734ecSArgyrios Kyrtzidis       case BO_LE:
794fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(true, resultTy);
795fa0734ecSArgyrios Kyrtzidis       }
796fa0734ecSArgyrios Kyrtzidis     }
797fa0734ecSArgyrios Kyrtzidis 
798fa0734ecSArgyrios Kyrtzidis     // Comparing an arbitrary integer to a region or label address is
799fa0734ecSArgyrios Kyrtzidis     // completely unknowable.
800fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
801fa0734ecSArgyrios Kyrtzidis   }
80273f018e3SArtem Dergachev   case loc::MemRegionValKind: {
80305785d16SDavid Blaikie     if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
804fa0734ecSArgyrios Kyrtzidis       // If one of the operands is a symbol and the other is a constant,
805fa0734ecSArgyrios Kyrtzidis       // build an expression for use by the constraint manager.
806f4963ff1SAlexander Shaposhnikov       if (SymbolRef lSym = lhs.getAsLocSymbol(true)) {
807f4963ff1SAlexander Shaposhnikov         if (BinaryOperator::isComparisonOp(op))
808fa0734ecSArgyrios Kyrtzidis           return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
809f4963ff1SAlexander Shaposhnikov         return UnknownVal();
810f4963ff1SAlexander Shaposhnikov       }
811fa0734ecSArgyrios Kyrtzidis       // Special case comparisons to NULL.
812fa0734ecSArgyrios Kyrtzidis       // This must come after the test if the LHS is a symbol, which is used to
813fa0734ecSArgyrios Kyrtzidis       // build constraints. The address of any non-symbolic region is guaranteed
814fa0734ecSArgyrios Kyrtzidis       // to be non-NULL.
815fa0734ecSArgyrios Kyrtzidis       if (rInt->isZeroConstant()) {
816acd080b9SJordan Rose         if (op == BO_Sub)
81701ddfa95SDenys Petrov           return evalCast(lhs, resultTy, QualType{});
818acd080b9SJordan Rose 
819acd080b9SJordan Rose         if (BinaryOperator::isComparisonOp(op)) {
820acd080b9SJordan Rose           QualType boolType = getContext().BoolTy;
82101ddfa95SDenys Petrov           NonLoc l = evalCast(lhs, boolType, QualType{}).castAs<NonLoc>();
822acd080b9SJordan Rose           NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>();
823acd080b9SJordan Rose           return evalBinOpNN(state, op, l, r, resultTy);
824fa0734ecSArgyrios Kyrtzidis         }
825fa0734ecSArgyrios Kyrtzidis       }
826fa0734ecSArgyrios Kyrtzidis 
827fa0734ecSArgyrios Kyrtzidis       // Comparing a region to an arbitrary integer is completely unknowable.
828fa0734ecSArgyrios Kyrtzidis       return UnknownVal();
829fa0734ecSArgyrios Kyrtzidis     }
830fa0734ecSArgyrios Kyrtzidis 
831fa0734ecSArgyrios Kyrtzidis     // Get both values as regions, if possible.
832fa0734ecSArgyrios Kyrtzidis     const MemRegion *LeftMR = lhs.getAsRegion();
83373f018e3SArtem Dergachev     assert(LeftMR && "MemRegionValKind SVal doesn't have a region!");
834fa0734ecSArgyrios Kyrtzidis 
835fa0734ecSArgyrios Kyrtzidis     const MemRegion *RightMR = rhs.getAsRegion();
836fa0734ecSArgyrios Kyrtzidis     if (!RightMR)
837fa0734ecSArgyrios Kyrtzidis       // The RHS is probably a label, which in theory could address a region.
838fa0734ecSArgyrios Kyrtzidis       // FIXME: we can probably make a more useful statement about non-code
839fa0734ecSArgyrios Kyrtzidis       // regions, though.
840fa0734ecSArgyrios Kyrtzidis       return UnknownVal();
841fa0734ecSArgyrios Kyrtzidis 
842fa0734ecSArgyrios Kyrtzidis     const MemRegion *LeftBase = LeftMR->getBaseRegion();
843fa0734ecSArgyrios Kyrtzidis     const MemRegion *RightBase = RightMR->getBaseRegion();
8443b4c3ea2SJordan Rose     const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
8453b4c3ea2SJordan Rose     const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
8463b4c3ea2SJordan Rose     const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
8473563fde6SAnna Zaks 
8483563fde6SAnna Zaks     // If the two regions are from different known memory spaces they cannot be
8493563fde6SAnna Zaks     // equal. Also, assume that no symbolic region (whose memory space is
8503563fde6SAnna Zaks     // unknown) is on the stack.
8513563fde6SAnna Zaks     if (LeftMS != RightMS &&
8523563fde6SAnna Zaks         ((LeftMS != UnknownMS && RightMS != UnknownMS) ||
8533563fde6SAnna Zaks          (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
854fa0734ecSArgyrios Kyrtzidis       switch (op) {
855fa0734ecSArgyrios Kyrtzidis       default:
856fa0734ecSArgyrios Kyrtzidis         return UnknownVal();
857fa0734ecSArgyrios Kyrtzidis       case BO_EQ:
858fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(false, resultTy);
859fa0734ecSArgyrios Kyrtzidis       case BO_NE:
860fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(true, resultTy);
861fa0734ecSArgyrios Kyrtzidis       }
862fa0734ecSArgyrios Kyrtzidis     }
863fa0734ecSArgyrios Kyrtzidis 
8643563fde6SAnna Zaks     // If both values wrap regions, see if they're from different base regions.
8653563fde6SAnna Zaks     // Note, heap base symbolic regions are assumed to not alias with
8663563fde6SAnna Zaks     // each other; for example, we assume that malloc returns different address
8673563fde6SAnna Zaks     // on each invocation.
868aacc03c9SArtem Dergachev     // FIXME: ObjC object pointers always reside on the heap, but currently
869aacc03c9SArtem Dergachev     // we treat their memory space as unknown, because symbolic pointers
870aacc03c9SArtem Dergachev     // to ObjC objects may alias. There should be a way to construct
871aacc03c9SArtem Dergachev     // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker
872aacc03c9SArtem Dergachev     // guesses memory space for ObjC object pointers manually instead of
873aacc03c9SArtem Dergachev     // relying on us.
8743563fde6SAnna Zaks     if (LeftBase != RightBase &&
8753563fde6SAnna Zaks         ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
876a7dcc996SAnna Zaks          (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
8779d96f843STed Kremenek       switch (op) {
8789d96f843STed Kremenek       default:
8793563fde6SAnna Zaks         return UnknownVal();
8809d96f843STed Kremenek       case BO_EQ:
8819d96f843STed Kremenek         return makeTruthVal(false, resultTy);
8829d96f843STed Kremenek       case BO_NE:
8839d96f843STed Kremenek         return makeTruthVal(true, resultTy);
8849d96f843STed Kremenek       }
8859d96f843STed Kremenek     }
886fa0734ecSArgyrios Kyrtzidis 
887bac964e1SAnna Zaks     // Handle special cases for when both regions are element regions.
888fa0734ecSArgyrios Kyrtzidis     const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
889bac964e1SAnna Zaks     const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR);
890bac964e1SAnna Zaks     if (RightER && LeftER) {
891fa0734ecSArgyrios Kyrtzidis       // Next, see if the two ERs have the same super-region and matching types.
892fa0734ecSArgyrios Kyrtzidis       // FIXME: This should do something useful even if the types don't match,
893fa0734ecSArgyrios Kyrtzidis       // though if both indexes are constant the RegionRawOffset path will
894fa0734ecSArgyrios Kyrtzidis       // give the correct answer.
895fa0734ecSArgyrios Kyrtzidis       if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
896fa0734ecSArgyrios Kyrtzidis           LeftER->getElementType() == RightER->getElementType()) {
897fa0734ecSArgyrios Kyrtzidis         // Get the left index and cast it to the correct type.
898fa0734ecSArgyrios Kyrtzidis         // If the index is unknown or undefined, bail out here.
899fa0734ecSArgyrios Kyrtzidis         SVal LeftIndexVal = LeftER->getIndex();
90005785d16SDavid Blaikie         Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
901fa0734ecSArgyrios Kyrtzidis         if (!LeftIndex)
902fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
90301ddfa95SDenys Petrov         LeftIndexVal = evalCast(*LeftIndex, ArrayIndexTy, QualType{});
9042fdacbc5SDavid Blaikie         LeftIndex = LeftIndexVal.getAs<NonLoc>();
905fa0734ecSArgyrios Kyrtzidis         if (!LeftIndex)
906fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
907fa0734ecSArgyrios Kyrtzidis 
908fa0734ecSArgyrios Kyrtzidis         // Do the same for the right index.
909fa0734ecSArgyrios Kyrtzidis         SVal RightIndexVal = RightER->getIndex();
91005785d16SDavid Blaikie         Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
911fa0734ecSArgyrios Kyrtzidis         if (!RightIndex)
912fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
91301ddfa95SDenys Petrov         RightIndexVal = evalCast(*RightIndex, ArrayIndexTy, QualType{});
9142fdacbc5SDavid Blaikie         RightIndex = RightIndexVal.getAs<NonLoc>();
915fa0734ecSArgyrios Kyrtzidis         if (!RightIndex)
916fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
917fa0734ecSArgyrios Kyrtzidis 
918fa0734ecSArgyrios Kyrtzidis         // Actually perform the operation.
919fa0734ecSArgyrios Kyrtzidis         // evalBinOpNN expects the two indexes to already be the right type.
920fa0734ecSArgyrios Kyrtzidis         return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
921fa0734ecSArgyrios Kyrtzidis       }
922bac964e1SAnna Zaks     }
923fa0734ecSArgyrios Kyrtzidis 
924bac964e1SAnna Zaks     // Special handling of the FieldRegions, even with symbolic offsets.
925bac964e1SAnna Zaks     const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
926bac964e1SAnna Zaks     const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR);
927bac964e1SAnna Zaks     if (RightFR && LeftFR) {
928bac964e1SAnna Zaks       SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy,
929bac964e1SAnna Zaks                                                *this);
930bac964e1SAnna Zaks       if (!R.isUnknown())
931bac964e1SAnna Zaks         return R;
932bac964e1SAnna Zaks     }
933bac964e1SAnna Zaks 
934bac964e1SAnna Zaks     // Compare the regions using the raw offsets.
935bac964e1SAnna Zaks     RegionOffset LeftOffset = LeftMR->getAsOffset();
936bac964e1SAnna Zaks     RegionOffset RightOffset = RightMR->getAsOffset();
937fa0734ecSArgyrios Kyrtzidis 
9380dbb783cSCraig Topper     if (LeftOffset.getRegion() != nullptr &&
939bac964e1SAnna Zaks         LeftOffset.getRegion() == RightOffset.getRegion() &&
940bac964e1SAnna Zaks         !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) {
941bac964e1SAnna Zaks       int64_t left = LeftOffset.getOffset();
942bac964e1SAnna Zaks       int64_t right = RightOffset.getOffset();
943fa0734ecSArgyrios Kyrtzidis 
944fa0734ecSArgyrios Kyrtzidis       switch (op) {
945fa0734ecSArgyrios Kyrtzidis         default:
946fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
947fa0734ecSArgyrios Kyrtzidis         case BO_LT:
948fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left < right, resultTy);
949fa0734ecSArgyrios Kyrtzidis         case BO_GT:
950fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left > right, resultTy);
951fa0734ecSArgyrios Kyrtzidis         case BO_LE:
952fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left <= right, resultTy);
953fa0734ecSArgyrios Kyrtzidis         case BO_GE:
954fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left >= right, resultTy);
955fa0734ecSArgyrios Kyrtzidis         case BO_EQ:
956fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left == right, resultTy);
957fa0734ecSArgyrios Kyrtzidis         case BO_NE:
958fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left != right, resultTy);
959fa0734ecSArgyrios Kyrtzidis       }
960fa0734ecSArgyrios Kyrtzidis     }
961fa0734ecSArgyrios Kyrtzidis 
9623b4c3ea2SJordan Rose     // At this point we're not going to get a good answer, but we can try
9633b4c3ea2SJordan Rose     // conjuring an expression instead.
9643b4c3ea2SJordan Rose     SymbolRef LHSSym = lhs.getAsLocSymbol();
9653b4c3ea2SJordan Rose     SymbolRef RHSSym = rhs.getAsLocSymbol();
9663b4c3ea2SJordan Rose     if (LHSSym && RHSSym)
9673b4c3ea2SJordan Rose       return makeNonLoc(LHSSym, op, RHSSym, resultTy);
9683b4c3ea2SJordan Rose 
969fa0734ecSArgyrios Kyrtzidis     // If we get here, we have no way of comparing the regions.
970fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
971fa0734ecSArgyrios Kyrtzidis   }
972fa0734ecSArgyrios Kyrtzidis   }
973fa0734ecSArgyrios Kyrtzidis }
974fa0734ecSArgyrios Kyrtzidis 
97549b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
9769cbfdde2SValeriy Savchenko                                     BinaryOperator::Opcode op, Loc lhs,
9779cbfdde2SValeriy Savchenko                                     NonLoc rhs, QualType resultTy) {
97864c01f7bSDevin Coughlin   if (op >= BO_PtrMemD && op <= BO_PtrMemI) {
97964c01f7bSDevin Coughlin     if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) {
98064c01f7bSDevin Coughlin       if (PTMSV->isNullMemberPointer())
98164c01f7bSDevin Coughlin         return UndefinedVal();
9829cbfdde2SValeriy Savchenko 
9839cbfdde2SValeriy Savchenko       auto getFieldLValue = [&](const auto *FD) -> SVal {
98464c01f7bSDevin Coughlin         SVal Result = lhs;
98564c01f7bSDevin Coughlin 
98664c01f7bSDevin Coughlin         for (const auto &I : *PTMSV)
98764c01f7bSDevin Coughlin           Result = StateMgr.getStoreManager().evalDerivedToBase(
98864c01f7bSDevin Coughlin               Result, I->getType(), I->isVirtual());
9899cbfdde2SValeriy Savchenko 
99064c01f7bSDevin Coughlin         return state->getLValue(FD, Result);
9919cbfdde2SValeriy Savchenko       };
9929cbfdde2SValeriy Savchenko 
9939cbfdde2SValeriy Savchenko       if (const auto *FD = PTMSV->getDeclAs<FieldDecl>()) {
9949cbfdde2SValeriy Savchenko         return getFieldLValue(FD);
9959cbfdde2SValeriy Savchenko       }
9969cbfdde2SValeriy Savchenko       if (const auto *FD = PTMSV->getDeclAs<IndirectFieldDecl>()) {
9979cbfdde2SValeriy Savchenko         return getFieldLValue(FD);
99864c01f7bSDevin Coughlin       }
99964c01f7bSDevin Coughlin     }
100064c01f7bSDevin Coughlin 
100164c01f7bSDevin Coughlin     return rhs;
100264c01f7bSDevin Coughlin   }
100364c01f7bSDevin Coughlin 
1004686df322SJordan Rose   assert(!BinaryOperator::isComparisonOp(op) &&
1005686df322SJordan Rose          "arguments to comparison ops must be of the same type");
1006fa0734ecSArgyrios Kyrtzidis 
1007fa0734ecSArgyrios Kyrtzidis   // Special case: rhs is a zero constant.
1008fa0734ecSArgyrios Kyrtzidis   if (rhs.isZeroConstant())
1009fa0734ecSArgyrios Kyrtzidis     return lhs;
1010fa0734ecSArgyrios Kyrtzidis 
101121524676SGabor Horvath   // Perserve the null pointer so that it can be found by the DerefChecker.
101221524676SGabor Horvath   if (lhs.isZeroConstant())
101321524676SGabor Horvath     return lhs;
101421524676SGabor Horvath 
1015fa0734ecSArgyrios Kyrtzidis   // We are dealing with pointer arithmetic.
1016fa0734ecSArgyrios Kyrtzidis 
1017fa0734ecSArgyrios Kyrtzidis   // Handle pointer arithmetic on constant values.
101805785d16SDavid Blaikie   if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) {
101905785d16SDavid Blaikie     if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) {
1020fa0734ecSArgyrios Kyrtzidis       const llvm::APSInt &leftI = lhsInt->getValue();
1021fa0734ecSArgyrios Kyrtzidis       assert(leftI.isUnsigned());
1022fa0734ecSArgyrios Kyrtzidis       llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
1023fa0734ecSArgyrios Kyrtzidis 
1024fa0734ecSArgyrios Kyrtzidis       // Convert the bitwidth of rightI.  This should deal with overflow
1025fa0734ecSArgyrios Kyrtzidis       // since we are dealing with concrete values.
1026fa0734ecSArgyrios Kyrtzidis       rightI = rightI.extOrTrunc(leftI.getBitWidth());
1027fa0734ecSArgyrios Kyrtzidis 
1028fa0734ecSArgyrios Kyrtzidis       // Offset the increment by the pointer size.
1029fa0734ecSArgyrios Kyrtzidis       llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
103021524676SGabor Horvath       QualType pointeeType = resultTy->getPointeeType();
103121524676SGabor Horvath       Multiplicand = getContext().getTypeSizeInChars(pointeeType).getQuantity();
1032fa0734ecSArgyrios Kyrtzidis       rightI *= Multiplicand;
1033fa0734ecSArgyrios Kyrtzidis 
1034fa0734ecSArgyrios Kyrtzidis       // Compute the adjusted pointer.
1035fa0734ecSArgyrios Kyrtzidis       switch (op) {
1036fa0734ecSArgyrios Kyrtzidis         case BO_Add:
1037fa0734ecSArgyrios Kyrtzidis           rightI = leftI + rightI;
1038fa0734ecSArgyrios Kyrtzidis           break;
1039fa0734ecSArgyrios Kyrtzidis         case BO_Sub:
1040fa0734ecSArgyrios Kyrtzidis           rightI = leftI - rightI;
1041fa0734ecSArgyrios Kyrtzidis           break;
1042fa0734ecSArgyrios Kyrtzidis         default:
1043fa0734ecSArgyrios Kyrtzidis           llvm_unreachable("Invalid pointer arithmetic operation");
1044fa0734ecSArgyrios Kyrtzidis       }
1045fa0734ecSArgyrios Kyrtzidis       return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
1046fa0734ecSArgyrios Kyrtzidis     }
1047fa0734ecSArgyrios Kyrtzidis   }
1048fa0734ecSArgyrios Kyrtzidis 
1049fa0734ecSArgyrios Kyrtzidis   // Handle cases where 'lhs' is a region.
1050fa0734ecSArgyrios Kyrtzidis   if (const MemRegion *region = lhs.getAsRegion()) {
10512fdacbc5SDavid Blaikie     rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
1052fa0734ecSArgyrios Kyrtzidis     SVal index = UnknownVal();
10536dd11048SArtem Dergachev     const SubRegion *superR = nullptr;
10547333a9eaSArtem Dergachev     // We need to know the type of the pointer in order to add an integer to it.
10557333a9eaSArtem Dergachev     // Depending on the type, different amount of bytes is added.
1056fa0734ecSArgyrios Kyrtzidis     QualType elementType;
1057fa0734ecSArgyrios Kyrtzidis 
1058fa0734ecSArgyrios Kyrtzidis     if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
105957a4a152STed Kremenek       assert(op == BO_Add || op == BO_Sub);
106057a4a152STed Kremenek       index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
1061fa0734ecSArgyrios Kyrtzidis                           getArrayIndexType());
10626dd11048SArtem Dergachev       superR = cast<SubRegion>(elemReg->getSuperRegion());
1063fa0734ecSArgyrios Kyrtzidis       elementType = elemReg->getElementType();
1064fa0734ecSArgyrios Kyrtzidis     }
1065fa0734ecSArgyrios Kyrtzidis     else if (isa<SubRegion>(region)) {
1066c4b28a8fSGabor Horvath       assert(op == BO_Add || op == BO_Sub);
1067c4b28a8fSGabor Horvath       index = (op == BO_Add) ? rhs : evalMinus(rhs);
10686dd11048SArtem Dergachev       superR = cast<SubRegion>(region);
10697333a9eaSArtem Dergachev       // TODO: Is this actually reliable? Maybe improving our MemRegion
10707333a9eaSArtem Dergachev       // hierarchy to provide typed regions for all non-void pointers would be
10717333a9eaSArtem Dergachev       // better. For instance, we cannot extend this towards LocAsInteger
10727333a9eaSArtem Dergachev       // operations, where result type of the expression is integer.
1073d1a08b6eSJordan Rose       if (resultTy->isAnyPointerType())
1074d1a08b6eSJordan Rose         elementType = resultTy->getPointeeType();
1075fa0734ecSArgyrios Kyrtzidis     }
1076fa0734ecSArgyrios Kyrtzidis 
1077df1bb8a6SArtem Dergachev     // Represent arithmetic on void pointers as arithmetic on char pointers.
1078df1bb8a6SArtem Dergachev     // It is fine when a TypedValueRegion of char value type represents
1079df1bb8a6SArtem Dergachev     // a void pointer. Note that arithmetic on void pointers is a GCC extension.
1080df1bb8a6SArtem Dergachev     if (elementType->isVoidType())
1081df1bb8a6SArtem Dergachev       elementType = getContext().CharTy;
1082df1bb8a6SArtem Dergachev 
108305785d16SDavid Blaikie     if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) {
1084fa0734ecSArgyrios Kyrtzidis       return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
1085fa0734ecSArgyrios Kyrtzidis                                                        superR, getContext()));
1086fa0734ecSArgyrios Kyrtzidis     }
1087fa0734ecSArgyrios Kyrtzidis   }
1088fa0734ecSArgyrios Kyrtzidis   return UnknownVal();
1089fa0734ecSArgyrios Kyrtzidis }
1090fa0734ecSArgyrios Kyrtzidis 
109149b1e38eSTed Kremenek const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
1092fa0734ecSArgyrios Kyrtzidis                                                    SVal V) {
10939ff67a9dSGeorge Karpenkov   V = simplifySVal(state, V);
1094fa0734ecSArgyrios Kyrtzidis   if (V.isUnknownOrUndef())
10950dbb783cSCraig Topper     return nullptr;
1096fa0734ecSArgyrios Kyrtzidis 
109705785d16SDavid Blaikie   if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
1098fa0734ecSArgyrios Kyrtzidis     return &X->getValue();
1099fa0734ecSArgyrios Kyrtzidis 
110005785d16SDavid Blaikie   if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
1101fa0734ecSArgyrios Kyrtzidis     return &X->getValue();
1102fa0734ecSArgyrios Kyrtzidis 
1103fa0734ecSArgyrios Kyrtzidis   if (SymbolRef Sym = V.getAsSymbol())
1104244e1d7dSTed Kremenek     return state->getConstraintManager().getSymVal(state, Sym);
1105fa0734ecSArgyrios Kyrtzidis 
1106c0402c69SDominic Chen   // FIXME: Add support for SymExprs.
11070dbb783cSCraig Topper   return nullptr;
1108fa0734ecSArgyrios Kyrtzidis }
110912294f8dSArtem Dergachev 
111012294f8dSArtem Dergachev SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) {
111112294f8dSArtem Dergachev   // For now, this function tries to constant-fold symbols inside a
111212294f8dSArtem Dergachev   // nonloc::SymbolVal, and does nothing else. More simplifications should
111312294f8dSArtem Dergachev   // be possible, such as constant-folding an index in an ElementRegion.
111412294f8dSArtem Dergachev 
111512294f8dSArtem Dergachev   class Simplifier : public FullSValVisitor<Simplifier, SVal> {
111612294f8dSArtem Dergachev     ProgramStateRef State;
111712294f8dSArtem Dergachev     SValBuilder &SVB;
111812294f8dSArtem Dergachev 
111922746d7dSArtem Dergachev     // Cache results for the lifetime of the Simplifier. Results change every
112022746d7dSArtem Dergachev     // time new constraints are added to the program state, which is the whole
112122746d7dSArtem Dergachev     // point of simplifying, and for that very reason it's pointless to maintain
112222746d7dSArtem Dergachev     // the same cache for the duration of the whole analysis.
112322746d7dSArtem Dergachev     llvm::DenseMap<SymbolRef, SVal> Cached;
112422746d7dSArtem Dergachev 
112516a1f64cSArtem Dergachev     static bool isUnchanged(SymbolRef Sym, SVal Val) {
112616a1f64cSArtem Dergachev       return Sym == Val.getAsSymbol();
112716a1f64cSArtem Dergachev     }
112816a1f64cSArtem Dergachev 
11299fe9a95fSArtem Dergachev     SVal cache(SymbolRef Sym, SVal V) {
11309fe9a95fSArtem Dergachev       Cached[Sym] = V;
11319fe9a95fSArtem Dergachev       return V;
11329fe9a95fSArtem Dergachev     }
11339fe9a95fSArtem Dergachev 
11349fe9a95fSArtem Dergachev     SVal skip(SymbolRef Sym) {
11359fe9a95fSArtem Dergachev       return cache(Sym, SVB.makeSymbolVal(Sym));
11369fe9a95fSArtem Dergachev     }
11379fe9a95fSArtem Dergachev 
113812294f8dSArtem Dergachev   public:
113912294f8dSArtem Dergachev     Simplifier(ProgramStateRef State)
114012294f8dSArtem Dergachev         : State(State), SVB(State->getStateManager().getSValBuilder()) {}
114112294f8dSArtem Dergachev 
114212294f8dSArtem Dergachev     SVal VisitSymbolData(const SymbolData *S) {
11439fe9a95fSArtem Dergachev       // No cache here.
114412294f8dSArtem Dergachev       if (const llvm::APSInt *I =
1145d1163790SArtem Dergachev               SVB.getKnownValue(State, SVB.makeSymbolVal(S)))
114612294f8dSArtem Dergachev         return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I)
114712294f8dSArtem Dergachev                                             : (SVal)SVB.makeIntVal(*I);
114816a1f64cSArtem Dergachev       return SVB.makeSymbolVal(S);
114912294f8dSArtem Dergachev     }
115012294f8dSArtem Dergachev 
1151c0402c69SDominic Chen     // TODO: Support SymbolCast. Support IntSymExpr when/if we actually
1152c0402c69SDominic Chen     // start producing them.
115312294f8dSArtem Dergachev 
115412294f8dSArtem Dergachev     SVal VisitSymIntExpr(const SymIntExpr *S) {
115522746d7dSArtem Dergachev       auto I = Cached.find(S);
115622746d7dSArtem Dergachev       if (I != Cached.end())
115722746d7dSArtem Dergachev         return I->second;
115822746d7dSArtem Dergachev 
115912294f8dSArtem Dergachev       SVal LHS = Visit(S->getLHS());
11609fe9a95fSArtem Dergachev       if (isUnchanged(S->getLHS(), LHS))
11619fe9a95fSArtem Dergachev         return skip(S);
11629fe9a95fSArtem Dergachev 
116312294f8dSArtem Dergachev       SVal RHS;
116412294f8dSArtem Dergachev       // By looking at the APSInt in the right-hand side of S, we cannot
116512294f8dSArtem Dergachev       // figure out if it should be treated as a Loc or as a NonLoc.
116612294f8dSArtem Dergachev       // So make our guess by recalling that we cannot multiply pointers
116712294f8dSArtem Dergachev       // or compare a pointer to an integer.
116812294f8dSArtem Dergachev       if (Loc::isLocType(S->getLHS()->getType()) &&
116912294f8dSArtem Dergachev           BinaryOperator::isComparisonOp(S->getOpcode())) {
117012294f8dSArtem Dergachev         // The usual conversion of $sym to &SymRegion{$sym}, as they have
117112294f8dSArtem Dergachev         // the same meaning for Loc-type symbols, but the latter form
117212294f8dSArtem Dergachev         // is preferred in SVal computations for being Loc itself.
117312294f8dSArtem Dergachev         if (SymbolRef Sym = LHS.getAsSymbol()) {
117412294f8dSArtem Dergachev           assert(Loc::isLocType(Sym->getType()));
117512294f8dSArtem Dergachev           LHS = SVB.makeLoc(Sym);
117612294f8dSArtem Dergachev         }
117712294f8dSArtem Dergachev         RHS = SVB.makeIntLocVal(S->getRHS());
117812294f8dSArtem Dergachev       } else {
117912294f8dSArtem Dergachev         RHS = SVB.makeIntVal(S->getRHS());
118012294f8dSArtem Dergachev       }
118122746d7dSArtem Dergachev 
11829fe9a95fSArtem Dergachev       return cache(
11839fe9a95fSArtem Dergachev           S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
118412294f8dSArtem Dergachev     }
118512294f8dSArtem Dergachev 
1186*ffc32efdSGabor Marton     SVal VisitIntSymExpr(const IntSymExpr *S) {
1187*ffc32efdSGabor Marton       auto I = Cached.find(S);
1188*ffc32efdSGabor Marton       if (I != Cached.end())
1189*ffc32efdSGabor Marton         return I->second;
1190*ffc32efdSGabor Marton 
1191*ffc32efdSGabor Marton       SVal RHS = Visit(S->getRHS());
1192*ffc32efdSGabor Marton       if (isUnchanged(S->getRHS(), RHS))
1193*ffc32efdSGabor Marton         return skip(S);
1194*ffc32efdSGabor Marton       SVal LHS = SVB.makeIntVal(S->getLHS());
1195*ffc32efdSGabor Marton       return cache(
1196*ffc32efdSGabor Marton           S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
1197*ffc32efdSGabor Marton     }
1198*ffc32efdSGabor Marton 
119912294f8dSArtem Dergachev     SVal VisitSymSymExpr(const SymSymExpr *S) {
120022746d7dSArtem Dergachev       auto I = Cached.find(S);
120122746d7dSArtem Dergachev       if (I != Cached.end())
120222746d7dSArtem Dergachev         return I->second;
120322746d7dSArtem Dergachev 
120405220a90SArtem Dergachev       // For now don't try to simplify mixed Loc/NonLoc expressions
120505220a90SArtem Dergachev       // because they often appear from LocAsInteger operations
120605220a90SArtem Dergachev       // and we don't know how to combine a LocAsInteger
120705220a90SArtem Dergachev       // with a concrete value.
120805220a90SArtem Dergachev       if (Loc::isLocType(S->getLHS()->getType()) !=
12099fe9a95fSArtem Dergachev           Loc::isLocType(S->getRHS()->getType()))
12109fe9a95fSArtem Dergachev         return skip(S);
121105220a90SArtem Dergachev 
121212294f8dSArtem Dergachev       SVal LHS = Visit(S->getLHS());
121312294f8dSArtem Dergachev       SVal RHS = Visit(S->getRHS());
12149fe9a95fSArtem Dergachev       if (isUnchanged(S->getLHS(), LHS) && isUnchanged(S->getRHS(), RHS))
12159fe9a95fSArtem Dergachev         return skip(S);
12169fe9a95fSArtem Dergachev 
12179fe9a95fSArtem Dergachev       return cache(
12189fe9a95fSArtem Dergachev           S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
121912294f8dSArtem Dergachev     }
122012294f8dSArtem Dergachev 
122112294f8dSArtem Dergachev     SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); }
122212294f8dSArtem Dergachev 
122312294f8dSArtem Dergachev     SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); }
122412294f8dSArtem Dergachev 
122512294f8dSArtem Dergachev     SVal VisitNonLocSymbolVal(nonloc::SymbolVal V) {
122612294f8dSArtem Dergachev       // Simplification is much more costly than computing complexity.
122712294f8dSArtem Dergachev       // For high complexity, it may be not worth it.
122812294f8dSArtem Dergachev       return Visit(V.getSymbol());
122912294f8dSArtem Dergachev     }
123012294f8dSArtem Dergachev 
123112294f8dSArtem Dergachev     SVal VisitSVal(SVal V) { return V; }
123212294f8dSArtem Dergachev   };
123312294f8dSArtem Dergachev 
123416a1f64cSArtem Dergachev   // A crude way of preventing this function from calling itself from evalBinOp.
123516a1f64cSArtem Dergachev   static bool isReentering = false;
123616a1f64cSArtem Dergachev   if (isReentering)
123716a1f64cSArtem Dergachev     return V;
123816a1f64cSArtem Dergachev 
123916a1f64cSArtem Dergachev   isReentering = true;
124016a1f64cSArtem Dergachev   SVal SimplifiedV = Simplifier(State).Visit(V);
124116a1f64cSArtem Dergachev   isReentering = false;
124216a1f64cSArtem Dergachev 
124316a1f64cSArtem Dergachev   return SimplifiedV;
124412294f8dSArtem Dergachev }
1245