1fa0734ecSArgyrios Kyrtzidis // SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- C++ -*-
2fa0734ecSArgyrios Kyrtzidis //
3fa0734ecSArgyrios Kyrtzidis //                     The LLVM Compiler Infrastructure
4fa0734ecSArgyrios Kyrtzidis //
5fa0734ecSArgyrios Kyrtzidis // This file is distributed under the University of Illinois Open Source
6fa0734ecSArgyrios Kyrtzidis // License. See LICENSE.TXT for details.
7fa0734ecSArgyrios Kyrtzidis //
8fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
9fa0734ecSArgyrios Kyrtzidis //
10fa0734ecSArgyrios Kyrtzidis //  This file defines SimpleSValBuilder, a basic implementation of SValBuilder.
11fa0734ecSArgyrios Kyrtzidis //
12fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
13fa0734ecSArgyrios Kyrtzidis 
14f8cbac4bSTed Kremenek #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
152bbccca9SAdam Balogh #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
163a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
17001fd5b4STed Kremenek #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
182bbccca9SAdam Balogh #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
1912294f8dSArtem Dergachev #include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h"
20fa0734ecSArgyrios Kyrtzidis 
21fa0734ecSArgyrios Kyrtzidis using namespace clang;
22fa0734ecSArgyrios Kyrtzidis using namespace ento;
23fa0734ecSArgyrios Kyrtzidis 
24fa0734ecSArgyrios Kyrtzidis namespace {
25fa0734ecSArgyrios Kyrtzidis class SimpleSValBuilder : public SValBuilder {
26fa0734ecSArgyrios Kyrtzidis protected:
27fb6b25b5SCraig Topper   SVal dispatchCast(SVal val, QualType castTy) override;
28fb6b25b5SCraig Topper   SVal evalCastFromNonLoc(NonLoc val, QualType castTy) override;
29fb6b25b5SCraig Topper   SVal evalCastFromLoc(Loc val, QualType castTy) override;
30fa0734ecSArgyrios Kyrtzidis 
31fa0734ecSArgyrios Kyrtzidis public:
32fa0734ecSArgyrios Kyrtzidis   SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
33001fd5b4STed Kremenek                     ProgramStateManager &stateMgr)
34fa0734ecSArgyrios Kyrtzidis                     : SValBuilder(alloc, context, stateMgr) {}
35637d1e66SAngel Garcia Gomez   ~SimpleSValBuilder() override {}
36fa0734ecSArgyrios Kyrtzidis 
37fb6b25b5SCraig Topper   SVal evalMinus(NonLoc val) override;
38fb6b25b5SCraig Topper   SVal evalComplement(NonLoc val) override;
39fb6b25b5SCraig Topper   SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
40fb6b25b5SCraig Topper                    NonLoc lhs, NonLoc rhs, QualType resultTy) override;
41fb6b25b5SCraig Topper   SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
42fb6b25b5SCraig Topper                    Loc lhs, Loc rhs, QualType resultTy) override;
43fb6b25b5SCraig Topper   SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
44fb6b25b5SCraig Topper                    Loc lhs, NonLoc rhs, QualType resultTy) override;
45fa0734ecSArgyrios Kyrtzidis 
46fa0734ecSArgyrios Kyrtzidis   /// getKnownValue - evaluates a given SVal. If the SVal has only one possible
47fa0734ecSArgyrios Kyrtzidis   ///  (integer) value, that value is returned. Otherwise, returns NULL.
48fb6b25b5SCraig Topper   const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override;
49fa0734ecSArgyrios Kyrtzidis 
5012294f8dSArtem Dergachev   /// Recursively descends into symbolic expressions and replaces symbols
5112294f8dSArtem Dergachev   /// with their known values (in the sense of the getKnownValue() method).
5212294f8dSArtem Dergachev   SVal simplifySVal(ProgramStateRef State, SVal V) override;
5312294f8dSArtem Dergachev 
54fa0734ecSArgyrios Kyrtzidis   SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
55fa0734ecSArgyrios Kyrtzidis                      const llvm::APSInt &RHS, QualType resultTy);
56fa0734ecSArgyrios Kyrtzidis };
57fa0734ecSArgyrios Kyrtzidis } // end anonymous namespace
58fa0734ecSArgyrios Kyrtzidis 
59fa0734ecSArgyrios Kyrtzidis SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
60fa0734ecSArgyrios Kyrtzidis                                            ASTContext &context,
61001fd5b4STed Kremenek                                            ProgramStateManager &stateMgr) {
62fa0734ecSArgyrios Kyrtzidis   return new SimpleSValBuilder(alloc, context, stateMgr);
63fa0734ecSArgyrios Kyrtzidis }
64fa0734ecSArgyrios Kyrtzidis 
65fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
66fa0734ecSArgyrios Kyrtzidis // Transfer function for Casts.
67fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
68fa0734ecSArgyrios Kyrtzidis 
69c95a6c4cSAnna Zaks SVal SimpleSValBuilder::dispatchCast(SVal Val, QualType CastTy) {
702fdacbc5SDavid Blaikie   assert(Val.getAs<Loc>() || Val.getAs<NonLoc>());
712fdacbc5SDavid Blaikie   return Val.getAs<Loc>() ? evalCastFromLoc(Val.castAs<Loc>(), CastTy)
722fdacbc5SDavid Blaikie                            : evalCastFromNonLoc(Val.castAs<NonLoc>(), CastTy);
73c25efcccSAnna Zaks }
74c25efcccSAnna Zaks 
755ad574c0SZhanyong Wan SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
7685a203ebSZhanyong Wan   bool isLocType = Loc::isLocType(castTy);
7764c01f7bSDevin Coughlin   if (val.getAs<nonloc::PointerToMember>())
7864c01f7bSDevin Coughlin     return val;
7964c01f7bSDevin Coughlin 
8005785d16SDavid Blaikie   if (Optional<nonloc::LocAsInteger> LI = val.getAs<nonloc::LocAsInteger>()) {
81fa0734ecSArgyrios Kyrtzidis     if (isLocType)
82fa0734ecSArgyrios Kyrtzidis       return LI->getLoc();
83fa0734ecSArgyrios Kyrtzidis     // FIXME: Correctly support promotions/truncations.
8459d10a4cSAlexander Shaposhnikov     unsigned castSize = Context.getIntWidth(castTy);
85fa0734ecSArgyrios Kyrtzidis     if (castSize == LI->getNumBits())
86fa0734ecSArgyrios Kyrtzidis       return val;
87fa0734ecSArgyrios Kyrtzidis     return makeLocAsInteger(LI->getLoc(), castSize);
88fa0734ecSArgyrios Kyrtzidis   }
89fa0734ecSArgyrios Kyrtzidis 
90fa0734ecSArgyrios Kyrtzidis   if (const SymExpr *se = val.getAsSymbolicExpression()) {
91a808e165STed Kremenek     QualType T = Context.getCanonicalType(se->getType());
926af472aaSAnna Zaks     // If types are the same or both are integers, ignore the cast.
93fa0734ecSArgyrios Kyrtzidis     // FIXME: Remove this hack when we support symbolic truncation/extension.
94fa0734ecSArgyrios Kyrtzidis     // HACK: If both castTy and T are integers, ignore the cast.  This is
95fa0734ecSArgyrios Kyrtzidis     // not a permanent solution.  Eventually we want to precisely handle
96fa0734ecSArgyrios Kyrtzidis     // extension/truncation of symbolic integers.  This prevents us from losing
97fa0734ecSArgyrios Kyrtzidis     // precision when we assign 'x = y' and 'y' is symbolic and x and y are
98fa0734ecSArgyrios Kyrtzidis     // different integer types.
996af472aaSAnna Zaks    if (haveSameType(T, castTy))
100fa0734ecSArgyrios Kyrtzidis       return val;
101fa0734ecSArgyrios Kyrtzidis 
102c25efcccSAnna Zaks     if (!isLocType)
103c25efcccSAnna Zaks       return makeNonLoc(se, T, castTy);
104fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
105fa0734ecSArgyrios Kyrtzidis   }
106fa0734ecSArgyrios Kyrtzidis 
107d4733638SAlp Toker   // If value is a non-integer constant, produce unknown.
1082fdacbc5SDavid Blaikie   if (!val.getAs<nonloc::ConcreteInt>())
109fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
110fa0734ecSArgyrios Kyrtzidis 
1112317f30fSTed Kremenek   // Handle casts to a boolean type.
1122317f30fSTed Kremenek   if (castTy->isBooleanType()) {
1132fdacbc5SDavid Blaikie     bool b = val.castAs<nonloc::ConcreteInt>().getValue().getBoolValue();
1142317f30fSTed Kremenek     return makeTruthVal(b, castTy);
1152317f30fSTed Kremenek   }
1162317f30fSTed Kremenek 
117394256ccSAnna Zaks   // Only handle casts from integers to integers - if val is an integer constant
118d4733638SAlp Toker   // being cast to a non-integer type, produce unknown.
11961e221f6SJordan Rose   if (!isLocType && !castTy->isIntegralOrEnumerationType())
120fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
121fa0734ecSArgyrios Kyrtzidis 
1222fdacbc5SDavid Blaikie   llvm::APSInt i = val.castAs<nonloc::ConcreteInt>().getValue();
1237e3c3ea3SJordy Rose   BasicVals.getAPSIntType(castTy).apply(i);
124fa0734ecSArgyrios Kyrtzidis 
125fa0734ecSArgyrios Kyrtzidis   if (isLocType)
126fa0734ecSArgyrios Kyrtzidis     return makeIntLocVal(i);
127fa0734ecSArgyrios Kyrtzidis   else
128fa0734ecSArgyrios Kyrtzidis     return makeIntVal(i);
129fa0734ecSArgyrios Kyrtzidis }
130fa0734ecSArgyrios Kyrtzidis 
1315ad574c0SZhanyong Wan SVal SimpleSValBuilder::evalCastFromLoc(Loc val, QualType castTy) {
132fa0734ecSArgyrios Kyrtzidis 
133fa0734ecSArgyrios Kyrtzidis   // Casts from pointers -> pointers, just return the lval.
134fa0734ecSArgyrios Kyrtzidis   //
135fa0734ecSArgyrios Kyrtzidis   // Casts from pointers -> references, just return the lval.  These
136fa0734ecSArgyrios Kyrtzidis   //   can be introduced by the frontend for corner cases, e.g
137fa0734ecSArgyrios Kyrtzidis   //   casting from va_list* to __builtin_va_list&.
138fa0734ecSArgyrios Kyrtzidis   //
13985a203ebSZhanyong Wan   if (Loc::isLocType(castTy) || castTy->isReferenceType())
140fa0734ecSArgyrios Kyrtzidis     return val;
141fa0734ecSArgyrios Kyrtzidis 
142fa0734ecSArgyrios Kyrtzidis   // FIXME: Handle transparent unions where a value can be "transparently"
143fa0734ecSArgyrios Kyrtzidis   //  lifted into a union type.
144fa0734ecSArgyrios Kyrtzidis   if (castTy->isUnionType())
145fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
146fa0734ecSArgyrios Kyrtzidis 
147acd080b9SJordan Rose   // Casting a Loc to a bool will almost always be true,
148acd080b9SJordan Rose   // unless this is a weak function or a symbolic region.
149acd080b9SJordan Rose   if (castTy->isBooleanType()) {
150acd080b9SJordan Rose     switch (val.getSubKind()) {
15173f018e3SArtem Dergachev       case loc::MemRegionValKind: {
152acd080b9SJordan Rose         const MemRegion *R = val.castAs<loc::MemRegionVal>().getRegion();
15373f018e3SArtem Dergachev         if (const FunctionCodeRegion *FTR = dyn_cast<FunctionCodeRegion>(R))
154acd080b9SJordan Rose           if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FTR->getDecl()))
155acd080b9SJordan Rose             if (FD->isWeak())
156acd080b9SJordan Rose               // FIXME: Currently we are using an extent symbol here,
157acd080b9SJordan Rose               // because there are no generic region address metadata
158acd080b9SJordan Rose               // symbols to use, only content metadata.
159acd080b9SJordan Rose               return nonloc::SymbolVal(SymMgr.getExtentSymbol(FTR));
160acd080b9SJordan Rose 
161acd080b9SJordan Rose         if (const SymbolicRegion *SymR = R->getSymbolicBase())
16235dbd0b1SArtem Dergachev           return makeNonLoc(SymR->getSymbol(), BO_NE,
16335dbd0b1SArtem Dergachev                             BasicVals.getZeroWithPtrWidth(), castTy);
164acd080b9SJordan Rose 
165acd080b9SJordan Rose         // FALL-THROUGH
166a65d5785SGalina Kistanova         LLVM_FALLTHROUGH;
167acd080b9SJordan Rose       }
168acd080b9SJordan Rose 
169acd080b9SJordan Rose       case loc::GotoLabelKind:
170d4733638SAlp Toker         // Labels and non-symbolic memory regions are always true.
171acd080b9SJordan Rose         return makeTruthVal(true, castTy);
172acd080b9SJordan Rose     }
173acd080b9SJordan Rose   }
174acd080b9SJordan Rose 
17561e221f6SJordan Rose   if (castTy->isIntegralOrEnumerationType()) {
17659d10a4cSAlexander Shaposhnikov     unsigned BitWidth = Context.getIntWidth(castTy);
177fa0734ecSArgyrios Kyrtzidis 
1782fdacbc5SDavid Blaikie     if (!val.getAs<loc::ConcreteInt>())
179fa0734ecSArgyrios Kyrtzidis       return makeLocAsInteger(val, BitWidth);
180fa0734ecSArgyrios Kyrtzidis 
1812fdacbc5SDavid Blaikie     llvm::APSInt i = val.castAs<loc::ConcreteInt>().getValue();
1827e3c3ea3SJordy Rose     BasicVals.getAPSIntType(castTy).apply(i);
183fa0734ecSArgyrios Kyrtzidis     return makeIntVal(i);
184fa0734ecSArgyrios Kyrtzidis   }
185fa0734ecSArgyrios Kyrtzidis 
186fa0734ecSArgyrios Kyrtzidis   // All other cases: return 'UnknownVal'.  This includes casting pointers
187fa0734ecSArgyrios Kyrtzidis   // to floats, which is probably badness it itself, but this is a good
188fa0734ecSArgyrios Kyrtzidis   // intermediate solution until we do something better.
189fa0734ecSArgyrios Kyrtzidis   return UnknownVal();
190fa0734ecSArgyrios Kyrtzidis }
191fa0734ecSArgyrios Kyrtzidis 
192fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
193fa0734ecSArgyrios Kyrtzidis // Transfer function for unary operators.
194fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
195fa0734ecSArgyrios Kyrtzidis 
196fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::evalMinus(NonLoc val) {
197fa0734ecSArgyrios Kyrtzidis   switch (val.getSubKind()) {
198fa0734ecSArgyrios Kyrtzidis   case nonloc::ConcreteIntKind:
1992fdacbc5SDavid Blaikie     return val.castAs<nonloc::ConcreteInt>().evalMinus(*this);
200fa0734ecSArgyrios Kyrtzidis   default:
201fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
202fa0734ecSArgyrios Kyrtzidis   }
203fa0734ecSArgyrios Kyrtzidis }
204fa0734ecSArgyrios Kyrtzidis 
205fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::evalComplement(NonLoc X) {
206fa0734ecSArgyrios Kyrtzidis   switch (X.getSubKind()) {
207fa0734ecSArgyrios Kyrtzidis   case nonloc::ConcreteIntKind:
2082fdacbc5SDavid Blaikie     return X.castAs<nonloc::ConcreteInt>().evalComplement(*this);
209fa0734ecSArgyrios Kyrtzidis   default:
210fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
211fa0734ecSArgyrios Kyrtzidis   }
212fa0734ecSArgyrios Kyrtzidis }
213fa0734ecSArgyrios Kyrtzidis 
214fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
215fa0734ecSArgyrios Kyrtzidis // Transfer function for binary operators.
216fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
217fa0734ecSArgyrios Kyrtzidis 
218fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
219fa0734ecSArgyrios Kyrtzidis                                     BinaryOperator::Opcode op,
220fa0734ecSArgyrios Kyrtzidis                                     const llvm::APSInt &RHS,
221fa0734ecSArgyrios Kyrtzidis                                     QualType resultTy) {
222fa0734ecSArgyrios Kyrtzidis   bool isIdempotent = false;
223fa0734ecSArgyrios Kyrtzidis 
224fa0734ecSArgyrios Kyrtzidis   // Check for a few special cases with known reductions first.
225fa0734ecSArgyrios Kyrtzidis   switch (op) {
226fa0734ecSArgyrios Kyrtzidis   default:
227fa0734ecSArgyrios Kyrtzidis     // We can't reduce this case; just treat it normally.
228fa0734ecSArgyrios Kyrtzidis     break;
229fa0734ecSArgyrios Kyrtzidis   case BO_Mul:
230fa0734ecSArgyrios Kyrtzidis     // a*0 and a*1
231fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
232fa0734ecSArgyrios Kyrtzidis       return makeIntVal(0, resultTy);
233fa0734ecSArgyrios Kyrtzidis     else if (RHS == 1)
234fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
235fa0734ecSArgyrios Kyrtzidis     break;
236fa0734ecSArgyrios Kyrtzidis   case BO_Div:
237fa0734ecSArgyrios Kyrtzidis     // a/0 and a/1
238fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
239fa0734ecSArgyrios Kyrtzidis       // This is also handled elsewhere.
240fa0734ecSArgyrios Kyrtzidis       return UndefinedVal();
241fa0734ecSArgyrios Kyrtzidis     else if (RHS == 1)
242fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
243fa0734ecSArgyrios Kyrtzidis     break;
244fa0734ecSArgyrios Kyrtzidis   case BO_Rem:
245fa0734ecSArgyrios Kyrtzidis     // a%0 and a%1
246fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
247fa0734ecSArgyrios Kyrtzidis       // This is also handled elsewhere.
248fa0734ecSArgyrios Kyrtzidis       return UndefinedVal();
249fa0734ecSArgyrios Kyrtzidis     else if (RHS == 1)
250fa0734ecSArgyrios Kyrtzidis       return makeIntVal(0, resultTy);
251fa0734ecSArgyrios Kyrtzidis     break;
252fa0734ecSArgyrios Kyrtzidis   case BO_Add:
253fa0734ecSArgyrios Kyrtzidis   case BO_Sub:
254fa0734ecSArgyrios Kyrtzidis   case BO_Shl:
255fa0734ecSArgyrios Kyrtzidis   case BO_Shr:
256fa0734ecSArgyrios Kyrtzidis   case BO_Xor:
257fa0734ecSArgyrios Kyrtzidis     // a+0, a-0, a<<0, a>>0, a^0
258fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
259fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
260fa0734ecSArgyrios Kyrtzidis     break;
261fa0734ecSArgyrios Kyrtzidis   case BO_And:
262fa0734ecSArgyrios Kyrtzidis     // a&0 and a&(~0)
263fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
264fa0734ecSArgyrios Kyrtzidis       return makeIntVal(0, resultTy);
265fa0734ecSArgyrios Kyrtzidis     else if (RHS.isAllOnesValue())
266fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
267fa0734ecSArgyrios Kyrtzidis     break;
268fa0734ecSArgyrios Kyrtzidis   case BO_Or:
269fa0734ecSArgyrios Kyrtzidis     // a|0 and a|(~0)
270fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
271fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
272fa0734ecSArgyrios Kyrtzidis     else if (RHS.isAllOnesValue()) {
273fa0734ecSArgyrios Kyrtzidis       const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
274fa0734ecSArgyrios Kyrtzidis       return nonloc::ConcreteInt(Result);
275fa0734ecSArgyrios Kyrtzidis     }
276fa0734ecSArgyrios Kyrtzidis     break;
277fa0734ecSArgyrios Kyrtzidis   }
278fa0734ecSArgyrios Kyrtzidis 
279fa0734ecSArgyrios Kyrtzidis   // Idempotent ops (like a*1) can still change the type of an expression.
2805ad574c0SZhanyong Wan   // Wrap the LHS up in a NonLoc again and let evalCastFromNonLoc do the
2815ad574c0SZhanyong Wan   // dirty work.
282d066f79cSAnna Zaks   if (isIdempotent)
283a636fbe7SAnna Zaks       return evalCastFromNonLoc(nonloc::SymbolVal(LHS), resultTy);
284fa0734ecSArgyrios Kyrtzidis 
285fa0734ecSArgyrios Kyrtzidis   // If we reach this point, the expression cannot be simplified.
28654569448SJordy Rose   // Make a SymbolVal for the entire expression, after converting the RHS.
28754569448SJordy Rose   const llvm::APSInt *ConvertedRHS = &RHS;
28854569448SJordy Rose   if (BinaryOperator::isComparisonOp(op)) {
28954569448SJordy Rose     // We're looking for a type big enough to compare the symbolic value
29054569448SJordy Rose     // with the given constant.
29154569448SJordy Rose     // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
29254569448SJordy Rose     ASTContext &Ctx = getContext();
293a808e165STed Kremenek     QualType SymbolType = LHS->getType();
29454569448SJordy Rose     uint64_t ValWidth = RHS.getBitWidth();
29554569448SJordy Rose     uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
29654569448SJordy Rose 
29754569448SJordy Rose     if (ValWidth < TypeWidth) {
29854569448SJordy Rose       // If the value is too small, extend it.
29954569448SJordy Rose       ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
30054569448SJordy Rose     } else if (ValWidth == TypeWidth) {
30154569448SJordy Rose       // If the value is signed but the symbol is unsigned, do the comparison
30254569448SJordy Rose       // in unsigned space. [C99 6.3.1.8]
30354569448SJordy Rose       // (For the opposite case, the value is already unsigned.)
30454569448SJordy Rose       if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
30554569448SJordy Rose         ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
30654569448SJordy Rose     }
30754569448SJordy Rose   } else
30854569448SJordy Rose     ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
30954569448SJordy Rose 
31054569448SJordy Rose   return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
311fa0734ecSArgyrios Kyrtzidis }
312fa0734ecSArgyrios Kyrtzidis 
3132bbccca9SAdam Balogh // See if Sym is known to be a relation Rel with Bound.
3142bbccca9SAdam Balogh static bool isInRelation(BinaryOperator::Opcode Rel, SymbolRef Sym,
3152bbccca9SAdam Balogh                          llvm::APSInt Bound, ProgramStateRef State) {
3162bbccca9SAdam Balogh   SValBuilder &SVB = State->getStateManager().getSValBuilder();
3172bbccca9SAdam Balogh   SVal Result =
3182bbccca9SAdam Balogh       SVB.evalBinOpNN(State, Rel, nonloc::SymbolVal(Sym),
3192bbccca9SAdam Balogh                       nonloc::ConcreteInt(Bound), SVB.getConditionType());
3202bbccca9SAdam Balogh   if (auto DV = Result.getAs<DefinedSVal>()) {
3212bbccca9SAdam Balogh     return !State->assume(*DV, false);
3222bbccca9SAdam Balogh   }
3232bbccca9SAdam Balogh   return false;
3242bbccca9SAdam Balogh }
3252bbccca9SAdam Balogh 
3262bbccca9SAdam Balogh // See if Sym is known to be within [min/4, max/4], where min and max
3272bbccca9SAdam Balogh // are the bounds of the symbol's integral type. With such symbols,
3282bbccca9SAdam Balogh // some manipulations can be performed without the risk of overflow.
3292bbccca9SAdam Balogh // assume() doesn't cause infinite recursion because we should be dealing
3302bbccca9SAdam Balogh // with simpler symbols on every recursive call.
3312bbccca9SAdam Balogh static bool isWithinConstantOverflowBounds(SymbolRef Sym,
3322bbccca9SAdam Balogh                                            ProgramStateRef State) {
3332bbccca9SAdam Balogh   SValBuilder &SVB = State->getStateManager().getSValBuilder();
3342bbccca9SAdam Balogh   BasicValueFactory &BV = SVB.getBasicValueFactory();
3352bbccca9SAdam Balogh 
3362bbccca9SAdam Balogh   QualType T = Sym->getType();
3372bbccca9SAdam Balogh   assert(T->isSignedIntegerOrEnumerationType() &&
3382bbccca9SAdam Balogh          "This only works with signed integers!");
3392bbccca9SAdam Balogh   APSIntType AT = BV.getAPSIntType(T);
3402bbccca9SAdam Balogh 
3412bbccca9SAdam Balogh   llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
3422bbccca9SAdam Balogh   return isInRelation(BO_LE, Sym, Max, State) &&
3432bbccca9SAdam Balogh          isInRelation(BO_GE, Sym, Min, State);
3442bbccca9SAdam Balogh }
3452bbccca9SAdam Balogh 
3462bbccca9SAdam Balogh // Same for the concrete integers: see if I is within [min/4, max/4].
3472bbccca9SAdam Balogh static bool isWithinConstantOverflowBounds(llvm::APSInt I) {
3482bbccca9SAdam Balogh   APSIntType AT(I);
3492bbccca9SAdam Balogh   assert(!AT.isUnsigned() &&
3502bbccca9SAdam Balogh          "This only works with signed integers!");
3512bbccca9SAdam Balogh 
3522bbccca9SAdam Balogh   llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
3532bbccca9SAdam Balogh   return (I <= Max) && (I >= -Max);
3542bbccca9SAdam Balogh }
3552bbccca9SAdam Balogh 
3562bbccca9SAdam Balogh static std::pair<SymbolRef, llvm::APSInt>
3572bbccca9SAdam Balogh decomposeSymbol(SymbolRef Sym, BasicValueFactory &BV) {
3582bbccca9SAdam Balogh   if (const auto *SymInt = dyn_cast<SymIntExpr>(Sym))
3592bbccca9SAdam Balogh     if (BinaryOperator::isAdditiveOp(SymInt->getOpcode()))
3602bbccca9SAdam Balogh       return std::make_pair(SymInt->getLHS(),
3612bbccca9SAdam Balogh                             (SymInt->getOpcode() == BO_Add) ?
3622bbccca9SAdam Balogh                             (SymInt->getRHS()) :
3632bbccca9SAdam Balogh                             (-SymInt->getRHS()));
3642bbccca9SAdam Balogh 
3652bbccca9SAdam Balogh   // Fail to decompose: "reduce" the problem to the "$x + 0" case.
3662bbccca9SAdam Balogh   return std::make_pair(Sym, BV.getValue(0, Sym->getType()));
3672bbccca9SAdam Balogh }
3682bbccca9SAdam Balogh 
3692bbccca9SAdam Balogh // Simplify "(LSym + LInt) Op (RSym + RInt)" assuming all values are of the
3702bbccca9SAdam Balogh // same signed integral type and no overflows occur (which should be checked
3712bbccca9SAdam Balogh // by the caller).
3722bbccca9SAdam Balogh static NonLoc doRearrangeUnchecked(ProgramStateRef State,
3732bbccca9SAdam Balogh                                    BinaryOperator::Opcode Op,
3742bbccca9SAdam Balogh                                    SymbolRef LSym, llvm::APSInt LInt,
3752bbccca9SAdam Balogh                                    SymbolRef RSym, llvm::APSInt RInt) {
3762bbccca9SAdam Balogh   SValBuilder &SVB = State->getStateManager().getSValBuilder();
3772bbccca9SAdam Balogh   BasicValueFactory &BV = SVB.getBasicValueFactory();
3782bbccca9SAdam Balogh   SymbolManager &SymMgr = SVB.getSymbolManager();
3792bbccca9SAdam Balogh 
3802bbccca9SAdam Balogh   QualType SymTy = LSym->getType();
3812bbccca9SAdam Balogh   assert(SymTy == RSym->getType() &&
3822bbccca9SAdam Balogh          "Symbols are not of the same type!");
3832bbccca9SAdam Balogh   assert(APSIntType(LInt) == BV.getAPSIntType(SymTy) &&
3842bbccca9SAdam Balogh          "Integers are not of the same type as symbols!");
3852bbccca9SAdam Balogh   assert(APSIntType(RInt) == BV.getAPSIntType(SymTy) &&
3862bbccca9SAdam Balogh          "Integers are not of the same type as symbols!");
3872bbccca9SAdam Balogh 
3882bbccca9SAdam Balogh   QualType ResultTy;
3892bbccca9SAdam Balogh   if (BinaryOperator::isComparisonOp(Op))
3902bbccca9SAdam Balogh     ResultTy = SVB.getConditionType();
3912bbccca9SAdam Balogh   else if (BinaryOperator::isAdditiveOp(Op))
3922bbccca9SAdam Balogh     ResultTy = SymTy;
3932bbccca9SAdam Balogh   else
3942bbccca9SAdam Balogh     llvm_unreachable("Operation not suitable for unchecked rearrangement!");
3952bbccca9SAdam Balogh 
3962bbccca9SAdam Balogh   // FIXME: Can we use assume() without getting into an infinite recursion?
3972bbccca9SAdam Balogh   if (LSym == RSym)
3982bbccca9SAdam Balogh     return SVB.evalBinOpNN(State, Op, nonloc::ConcreteInt(LInt),
3992bbccca9SAdam Balogh                            nonloc::ConcreteInt(RInt), ResultTy)
4002bbccca9SAdam Balogh         .castAs<NonLoc>();
4012bbccca9SAdam Balogh 
4022bbccca9SAdam Balogh   SymbolRef ResultSym = nullptr;
4032bbccca9SAdam Balogh   BinaryOperator::Opcode ResultOp;
4042bbccca9SAdam Balogh   llvm::APSInt ResultInt;
4052bbccca9SAdam Balogh   if (BinaryOperator::isComparisonOp(Op)) {
4062bbccca9SAdam Balogh     // Prefer comparing to a non-negative number.
4072bbccca9SAdam Balogh     // FIXME: Maybe it'd be better to have consistency in
4082bbccca9SAdam Balogh     // "$x - $y" vs. "$y - $x" because those are solver's keys.
4092bbccca9SAdam Balogh     if (LInt > RInt) {
4102bbccca9SAdam Balogh       ResultSym = SymMgr.getSymSymExpr(RSym, BO_Sub, LSym, SymTy);
4112bbccca9SAdam Balogh       ResultOp = BinaryOperator::reverseComparisonOp(Op);
4122bbccca9SAdam Balogh       ResultInt = LInt - RInt; // Opposite order!
4132bbccca9SAdam Balogh     } else {
4142bbccca9SAdam Balogh       ResultSym = SymMgr.getSymSymExpr(LSym, BO_Sub, RSym, SymTy);
4152bbccca9SAdam Balogh       ResultOp = Op;
4162bbccca9SAdam Balogh       ResultInt = RInt - LInt; // Opposite order!
4172bbccca9SAdam Balogh     }
4182bbccca9SAdam Balogh   } else {
4192bbccca9SAdam Balogh     ResultSym = SymMgr.getSymSymExpr(LSym, Op, RSym, SymTy);
4202bbccca9SAdam Balogh     ResultInt = (Op == BO_Add) ? (LInt + RInt) : (LInt - RInt);
4212bbccca9SAdam Balogh     ResultOp = BO_Add;
4222bbccca9SAdam Balogh     // Bring back the cosmetic difference.
4232bbccca9SAdam Balogh     if (ResultInt < 0) {
4242bbccca9SAdam Balogh       ResultInt = -ResultInt;
4252bbccca9SAdam Balogh       ResultOp = BO_Sub;
4262bbccca9SAdam Balogh     } else if (ResultInt == 0) {
4272bbccca9SAdam Balogh       // Shortcut: Simplify "$x + 0" to "$x".
4282bbccca9SAdam Balogh       return nonloc::SymbolVal(ResultSym);
4292bbccca9SAdam Balogh     }
4302bbccca9SAdam Balogh   }
4312bbccca9SAdam Balogh   const llvm::APSInt &PersistentResultInt = BV.getValue(ResultInt);
4322bbccca9SAdam Balogh   return nonloc::SymbolVal(
4332bbccca9SAdam Balogh       SymMgr.getSymIntExpr(ResultSym, ResultOp, PersistentResultInt, ResultTy));
4342bbccca9SAdam Balogh }
4352bbccca9SAdam Balogh 
4362bbccca9SAdam Balogh // Rearrange if symbol type matches the result type and if the operator is a
4372bbccca9SAdam Balogh // comparison operator, both symbol and constant must be within constant
4382bbccca9SAdam Balogh // overflow bounds.
4392bbccca9SAdam Balogh static bool shouldRearrange(ProgramStateRef State, BinaryOperator::Opcode Op,
4402bbccca9SAdam Balogh                             SymbolRef Sym, llvm::APSInt Int, QualType Ty) {
4412bbccca9SAdam Balogh   return Sym->getType() == Ty &&
4422bbccca9SAdam Balogh     (!BinaryOperator::isComparisonOp(Op) ||
4432bbccca9SAdam Balogh      (isWithinConstantOverflowBounds(Sym, State) &&
4442bbccca9SAdam Balogh       isWithinConstantOverflowBounds(Int)));
4452bbccca9SAdam Balogh }
4462bbccca9SAdam Balogh 
4472bbccca9SAdam Balogh static Optional<NonLoc> tryRearrange(ProgramStateRef State,
4482bbccca9SAdam Balogh                                      BinaryOperator::Opcode Op, NonLoc Lhs,
4492bbccca9SAdam Balogh                                      NonLoc Rhs, QualType ResultTy) {
4502bbccca9SAdam Balogh   ProgramStateManager &StateMgr = State->getStateManager();
4512bbccca9SAdam Balogh   SValBuilder &SVB = StateMgr.getSValBuilder();
4522bbccca9SAdam Balogh 
4532bbccca9SAdam Balogh   // We expect everything to be of the same type - this type.
4542bbccca9SAdam Balogh   QualType SingleTy;
4552bbccca9SAdam Balogh 
4562bbccca9SAdam Balogh   auto &Opts =
4572bbccca9SAdam Balogh     StateMgr.getOwningEngine()->getAnalysisManager().getAnalyzerOptions();
4582bbccca9SAdam Balogh 
459dcde8accSAdam Balogh   // FIXME: After putting complexity threshold to the symbols we can always
460dcde8accSAdam Balogh   //        rearrange additive operations but rearrange comparisons only if
461dcde8accSAdam Balogh   //        option is set.
462dcde8accSAdam Balogh   if(!Opts.shouldAggressivelySimplifyBinaryOperation())
463dcde8accSAdam Balogh     return None;
464dcde8accSAdam Balogh 
4652bbccca9SAdam Balogh   SymbolRef LSym = Lhs.getAsSymbol();
4662bbccca9SAdam Balogh   if (!LSym)
4672bbccca9SAdam Balogh     return None;
4682bbccca9SAdam Balogh 
469dcde8accSAdam Balogh   if (BinaryOperator::isComparisonOp(Op)) {
4702bbccca9SAdam Balogh     SingleTy = LSym->getType();
4712bbccca9SAdam Balogh     if (ResultTy != SVB.getConditionType())
4722bbccca9SAdam Balogh       return None;
4732bbccca9SAdam Balogh     // Initialize SingleTy later with a symbol's type.
4742bbccca9SAdam Balogh   } else if (BinaryOperator::isAdditiveOp(Op)) {
4752bbccca9SAdam Balogh     SingleTy = ResultTy;
47613e186c0SAdam Balogh     if (LSym->getType() != SingleTy)
47713e186c0SAdam Balogh       return None;
4782bbccca9SAdam Balogh     // Substracting unsigned integers is a nightmare.
4792bbccca9SAdam Balogh     if (!SingleTy->isSignedIntegerOrEnumerationType())
4802bbccca9SAdam Balogh       return None;
4812bbccca9SAdam Balogh   } else {
4822bbccca9SAdam Balogh     // Don't rearrange other operations.
4832bbccca9SAdam Balogh     return None;
4842bbccca9SAdam Balogh   }
4852bbccca9SAdam Balogh 
4862bbccca9SAdam Balogh   assert(!SingleTy.isNull() && "We should have figured out the type by now!");
4872bbccca9SAdam Balogh 
4882bbccca9SAdam Balogh   SymbolRef RSym = Rhs.getAsSymbol();
4892bbccca9SAdam Balogh   if (!RSym || RSym->getType() != SingleTy)
4902bbccca9SAdam Balogh     return None;
4912bbccca9SAdam Balogh 
4922bbccca9SAdam Balogh   BasicValueFactory &BV = State->getBasicVals();
4932bbccca9SAdam Balogh   llvm::APSInt LInt, RInt;
4942bbccca9SAdam Balogh   std::tie(LSym, LInt) = decomposeSymbol(LSym, BV);
4952bbccca9SAdam Balogh   std::tie(RSym, RInt) = decomposeSymbol(RSym, BV);
4962bbccca9SAdam Balogh   if (!shouldRearrange(State, Op, LSym, LInt, SingleTy) ||
4972bbccca9SAdam Balogh       !shouldRearrange(State, Op, RSym, RInt, SingleTy))
4982bbccca9SAdam Balogh     return None;
4992bbccca9SAdam Balogh 
5002bbccca9SAdam Balogh   // We know that no overflows can occur anymore.
5012bbccca9SAdam Balogh   return doRearrangeUnchecked(State, Op, LSym, LInt, RSym, RInt);
5022bbccca9SAdam Balogh }
5032bbccca9SAdam Balogh 
50449b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
505fa0734ecSArgyrios Kyrtzidis                                   BinaryOperator::Opcode op,
506fa0734ecSArgyrios Kyrtzidis                                   NonLoc lhs, NonLoc rhs,
507fa0734ecSArgyrios Kyrtzidis                                   QualType resultTy)  {
508f0e9ca86SAnna Zaks   NonLoc InputLHS = lhs;
509f0e9ca86SAnna Zaks   NonLoc InputRHS = rhs;
510f0e9ca86SAnna Zaks 
511fa0734ecSArgyrios Kyrtzidis   // Handle trivial case where left-side and right-side are the same.
512fa0734ecSArgyrios Kyrtzidis   if (lhs == rhs)
513fa0734ecSArgyrios Kyrtzidis     switch (op) {
514fa0734ecSArgyrios Kyrtzidis       default:
515fa0734ecSArgyrios Kyrtzidis         break;
516fa0734ecSArgyrios Kyrtzidis       case BO_EQ:
517fa0734ecSArgyrios Kyrtzidis       case BO_LE:
518fa0734ecSArgyrios Kyrtzidis       case BO_GE:
519fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(true, resultTy);
520fa0734ecSArgyrios Kyrtzidis       case BO_LT:
521fa0734ecSArgyrios Kyrtzidis       case BO_GT:
522fa0734ecSArgyrios Kyrtzidis       case BO_NE:
523fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(false, resultTy);
524fa0734ecSArgyrios Kyrtzidis       case BO_Xor:
525fa0734ecSArgyrios Kyrtzidis       case BO_Sub:
5267523d1a8SJordan Rose         if (resultTy->isIntegralOrEnumerationType())
527fa0734ecSArgyrios Kyrtzidis           return makeIntVal(0, resultTy);
5287523d1a8SJordan Rose         return evalCastFromNonLoc(makeIntVal(0, /*Unsigned=*/false), resultTy);
529fa0734ecSArgyrios Kyrtzidis       case BO_Or:
530fa0734ecSArgyrios Kyrtzidis       case BO_And:
5315ad574c0SZhanyong Wan         return evalCastFromNonLoc(lhs, resultTy);
532fa0734ecSArgyrios Kyrtzidis     }
533fa0734ecSArgyrios Kyrtzidis 
534fa0734ecSArgyrios Kyrtzidis   while (1) {
535fa0734ecSArgyrios Kyrtzidis     switch (lhs.getSubKind()) {
536fa0734ecSArgyrios Kyrtzidis     default:
537*bd3e5dbfSGeorge Karpenkov       return makeSymExprValNN(op, lhs, rhs, resultTy);
53864c01f7bSDevin Coughlin     case nonloc::PointerToMemberKind: {
53964c01f7bSDevin Coughlin       assert(rhs.getSubKind() == nonloc::PointerToMemberKind &&
54064c01f7bSDevin Coughlin              "Both SVals should have pointer-to-member-type");
54164c01f7bSDevin Coughlin       auto LPTM = lhs.castAs<nonloc::PointerToMember>(),
54264c01f7bSDevin Coughlin            RPTM = rhs.castAs<nonloc::PointerToMember>();
54364c01f7bSDevin Coughlin       auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData();
54464c01f7bSDevin Coughlin       switch (op) {
54564c01f7bSDevin Coughlin         case BO_EQ:
54664c01f7bSDevin Coughlin           return makeTruthVal(LPTMD == RPTMD, resultTy);
54764c01f7bSDevin Coughlin         case BO_NE:
54864c01f7bSDevin Coughlin           return makeTruthVal(LPTMD != RPTMD, resultTy);
54964c01f7bSDevin Coughlin         default:
55064c01f7bSDevin Coughlin           return UnknownVal();
55164c01f7bSDevin Coughlin       }
55264c01f7bSDevin Coughlin     }
553fa0734ecSArgyrios Kyrtzidis     case nonloc::LocAsIntegerKind: {
5542fdacbc5SDavid Blaikie       Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc();
555fa0734ecSArgyrios Kyrtzidis       switch (rhs.getSubKind()) {
556fa0734ecSArgyrios Kyrtzidis         case nonloc::LocAsIntegerKind:
55718d77984SAlexander Shaposhnikov           // FIXME: at the moment the implementation
55818d77984SAlexander Shaposhnikov           // of modeling "pointers as integers" is not complete.
55918d77984SAlexander Shaposhnikov           if (!BinaryOperator::isComparisonOp(op))
56018d77984SAlexander Shaposhnikov             return UnknownVal();
561fa0734ecSArgyrios Kyrtzidis           return evalBinOpLL(state, op, lhsL,
5622fdacbc5SDavid Blaikie                              rhs.castAs<nonloc::LocAsInteger>().getLoc(),
563fa0734ecSArgyrios Kyrtzidis                              resultTy);
564fa0734ecSArgyrios Kyrtzidis         case nonloc::ConcreteIntKind: {
56518d77984SAlexander Shaposhnikov           // FIXME: at the moment the implementation
56618d77984SAlexander Shaposhnikov           // of modeling "pointers as integers" is not complete.
56718d77984SAlexander Shaposhnikov           if (!BinaryOperator::isComparisonOp(op))
56818d77984SAlexander Shaposhnikov             return UnknownVal();
569fa0734ecSArgyrios Kyrtzidis           // Transform the integer into a location and compare.
5707333a9eaSArtem Dergachev           // FIXME: This only makes sense for comparisons. If we want to, say,
5717333a9eaSArtem Dergachev           // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it,
5727333a9eaSArtem Dergachev           // then pack it back into a LocAsInteger.
5732fdacbc5SDavid Blaikie           llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue();
5747e3c3ea3SJordy Rose           BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
575fa0734ecSArgyrios Kyrtzidis           return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
576fa0734ecSArgyrios Kyrtzidis         }
577fa0734ecSArgyrios Kyrtzidis         default:
578fa0734ecSArgyrios Kyrtzidis           switch (op) {
579fa0734ecSArgyrios Kyrtzidis             case BO_EQ:
580fa0734ecSArgyrios Kyrtzidis               return makeTruthVal(false, resultTy);
581fa0734ecSArgyrios Kyrtzidis             case BO_NE:
582fa0734ecSArgyrios Kyrtzidis               return makeTruthVal(true, resultTy);
583fa0734ecSArgyrios Kyrtzidis             default:
584fa0734ecSArgyrios Kyrtzidis               // This case also handles pointer arithmetic.
585*bd3e5dbfSGeorge Karpenkov               return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
586fa0734ecSArgyrios Kyrtzidis           }
587fa0734ecSArgyrios Kyrtzidis       }
588fa0734ecSArgyrios Kyrtzidis     }
589d066f79cSAnna Zaks     case nonloc::ConcreteIntKind: {
5902fdacbc5SDavid Blaikie       llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
591d066f79cSAnna Zaks 
59254569448SJordy Rose       // If we're dealing with two known constants, just perform the operation.
59354569448SJordy Rose       if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) {
59454569448SJordy Rose         llvm::APSInt RHSValue = *KnownRHSValue;
59554569448SJordy Rose         if (BinaryOperator::isComparisonOp(op)) {
59654569448SJordy Rose           // We're looking for a type big enough to compare the two values.
5977e3c3ea3SJordy Rose           // FIXME: This is not correct. char + short will result in a promotion
5987e3c3ea3SJordy Rose           // to int. Unfortunately we have lost types by this point.
5997e3c3ea3SJordy Rose           APSIntType CompareType = std::max(APSIntType(LHSValue),
6007e3c3ea3SJordy Rose                                             APSIntType(RHSValue));
6017e3c3ea3SJordy Rose           CompareType.apply(LHSValue);
6027e3c3ea3SJordy Rose           CompareType.apply(RHSValue);
60354569448SJordy Rose         } else if (!BinaryOperator::isShiftOp(op)) {
6047e3c3ea3SJordy Rose           APSIntType IntType = BasicVals.getAPSIntType(resultTy);
6057e3c3ea3SJordy Rose           IntType.apply(LHSValue);
6067e3c3ea3SJordy Rose           IntType.apply(RHSValue);
607d066f79cSAnna Zaks         }
608d066f79cSAnna Zaks 
60954569448SJordy Rose         const llvm::APSInt *Result =
61054569448SJordy Rose           BasicVals.evalAPSInt(op, LHSValue, RHSValue);
61154569448SJordy Rose         if (!Result)
61254569448SJordy Rose           return UndefinedVal();
61354569448SJordy Rose 
61454569448SJordy Rose         return nonloc::ConcreteInt(*Result);
61554569448SJordy Rose       }
616d066f79cSAnna Zaks 
617d066f79cSAnna Zaks       // Swap the left and right sides and flip the operator if doing so
618d066f79cSAnna Zaks       // allows us to better reason about the expression (this is a form
619d066f79cSAnna Zaks       // of expression canonicalization).
620d066f79cSAnna Zaks       // While we're at it, catch some special cases for non-commutative ops.
621d066f79cSAnna Zaks       switch (op) {
622d066f79cSAnna Zaks       case BO_LT:
623d066f79cSAnna Zaks       case BO_GT:
624d066f79cSAnna Zaks       case BO_LE:
625d066f79cSAnna Zaks       case BO_GE:
626604d0bbbSJordan Rose         op = BinaryOperator::reverseComparisonOp(op);
62754569448SJordy Rose         // FALL-THROUGH
628d066f79cSAnna Zaks       case BO_EQ:
629d066f79cSAnna Zaks       case BO_NE:
630d066f79cSAnna Zaks       case BO_Add:
631d066f79cSAnna Zaks       case BO_Mul:
632d066f79cSAnna Zaks       case BO_And:
633d066f79cSAnna Zaks       case BO_Xor:
634d066f79cSAnna Zaks       case BO_Or:
63554569448SJordy Rose         std::swap(lhs, rhs);
636d066f79cSAnna Zaks         continue;
637d066f79cSAnna Zaks       case BO_Shr:
63854569448SJordy Rose         // (~0)>>a
63954569448SJordy Rose         if (LHSValue.isAllOnesValue() && LHSValue.isSigned())
64054569448SJordy Rose           return evalCastFromNonLoc(lhs, resultTy);
641d066f79cSAnna Zaks         // FALL-THROUGH
642d066f79cSAnna Zaks       case BO_Shl:
64354569448SJordy Rose         // 0<<a and 0>>a
64454569448SJordy Rose         if (LHSValue == 0)
64554569448SJordy Rose           return evalCastFromNonLoc(lhs, resultTy);
646*bd3e5dbfSGeorge Karpenkov         return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
647d066f79cSAnna Zaks       default:
648*bd3e5dbfSGeorge Karpenkov         return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
649d066f79cSAnna Zaks       }
650d066f79cSAnna Zaks     }
651d066f79cSAnna Zaks     case nonloc::SymbolValKind: {
65254569448SJordy Rose       // We only handle LHS as simple symbols or SymIntExprs.
6532fdacbc5SDavid Blaikie       SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
654d066f79cSAnna Zaks 
655d066f79cSAnna Zaks       // LHS is a symbolic expression.
65654569448SJordy Rose       if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
657fa0734ecSArgyrios Kyrtzidis 
658fa0734ecSArgyrios Kyrtzidis         // Is this a logical not? (!x is represented as x == 0.)
659fa0734ecSArgyrios Kyrtzidis         if (op == BO_EQ && rhs.isZeroConstant()) {
660fa0734ecSArgyrios Kyrtzidis           // We know how to negate certain expressions. Simplify them here.
661fa0734ecSArgyrios Kyrtzidis 
662fa0734ecSArgyrios Kyrtzidis           BinaryOperator::Opcode opc = symIntExpr->getOpcode();
663fa0734ecSArgyrios Kyrtzidis           switch (opc) {
664fa0734ecSArgyrios Kyrtzidis           default:
665fa0734ecSArgyrios Kyrtzidis             // We don't know how to negate this operation.
666fa0734ecSArgyrios Kyrtzidis             // Just handle it as if it were a normal comparison to 0.
667fa0734ecSArgyrios Kyrtzidis             break;
668fa0734ecSArgyrios Kyrtzidis           case BO_LAnd:
669fa0734ecSArgyrios Kyrtzidis           case BO_LOr:
67083d382b1SDavid Blaikie             llvm_unreachable("Logical operators handled by branching logic.");
671fa0734ecSArgyrios Kyrtzidis           case BO_Assign:
672fa0734ecSArgyrios Kyrtzidis           case BO_MulAssign:
673fa0734ecSArgyrios Kyrtzidis           case BO_DivAssign:
674fa0734ecSArgyrios Kyrtzidis           case BO_RemAssign:
675fa0734ecSArgyrios Kyrtzidis           case BO_AddAssign:
676fa0734ecSArgyrios Kyrtzidis           case BO_SubAssign:
677fa0734ecSArgyrios Kyrtzidis           case BO_ShlAssign:
678fa0734ecSArgyrios Kyrtzidis           case BO_ShrAssign:
679fa0734ecSArgyrios Kyrtzidis           case BO_AndAssign:
680fa0734ecSArgyrios Kyrtzidis           case BO_XorAssign:
681fa0734ecSArgyrios Kyrtzidis           case BO_OrAssign:
682fa0734ecSArgyrios Kyrtzidis           case BO_Comma:
68383d382b1SDavid Blaikie             llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
684fa0734ecSArgyrios Kyrtzidis           case BO_PtrMemD:
685fa0734ecSArgyrios Kyrtzidis           case BO_PtrMemI:
68683d382b1SDavid Blaikie             llvm_unreachable("Pointer arithmetic not handled here.");
687fa0734ecSArgyrios Kyrtzidis           case BO_LT:
688fa0734ecSArgyrios Kyrtzidis           case BO_GT:
689fa0734ecSArgyrios Kyrtzidis           case BO_LE:
690fa0734ecSArgyrios Kyrtzidis           case BO_GE:
691fa0734ecSArgyrios Kyrtzidis           case BO_EQ:
692fa0734ecSArgyrios Kyrtzidis           case BO_NE:
693dc16628cSJordan Rose             assert(resultTy->isBooleanType() ||
694dc16628cSJordan Rose                    resultTy == getConditionType());
695dc16628cSJordan Rose             assert(symIntExpr->getType()->isBooleanType() ||
696dc16628cSJordan Rose                    getContext().hasSameUnqualifiedType(symIntExpr->getType(),
697dc16628cSJordan Rose                                                        getConditionType()));
698fa0734ecSArgyrios Kyrtzidis             // Negate the comparison and make a value.
699604d0bbbSJordan Rose             opc = BinaryOperator::negateComparisonOp(opc);
700fa0734ecSArgyrios Kyrtzidis             return makeNonLoc(symIntExpr->getLHS(), opc,
701fa0734ecSArgyrios Kyrtzidis                 symIntExpr->getRHS(), resultTy);
702fa0734ecSArgyrios Kyrtzidis           }
703fa0734ecSArgyrios Kyrtzidis         }
704fa0734ecSArgyrios Kyrtzidis 
705fa0734ecSArgyrios Kyrtzidis         // For now, only handle expressions whose RHS is a constant.
70654569448SJordy Rose         if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) {
707fa0734ecSArgyrios Kyrtzidis           // If both the LHS and the current expression are additive,
70854569448SJordy Rose           // fold their constants and try again.
709fa0734ecSArgyrios Kyrtzidis           if (BinaryOperator::isAdditiveOp(op)) {
710fa0734ecSArgyrios Kyrtzidis             BinaryOperator::Opcode lop = symIntExpr->getOpcode();
711fa0734ecSArgyrios Kyrtzidis             if (BinaryOperator::isAdditiveOp(lop)) {
71254569448SJordy Rose               // Convert the two constants to a common type, then combine them.
71354569448SJordy Rose 
714fa0734ecSArgyrios Kyrtzidis               // resultTy may not be the best type to convert to, but it's
715fa0734ecSArgyrios Kyrtzidis               // probably the best choice in expressions with mixed type
716fa0734ecSArgyrios Kyrtzidis               // (such as x+1U+2LL). The rules for implicit conversions should
717fa0734ecSArgyrios Kyrtzidis               // choose a reasonable type to preserve the expression, and will
718fa0734ecSArgyrios Kyrtzidis               // at least match how the value is going to be used.
7197e3c3ea3SJordy Rose               APSIntType IntType = BasicVals.getAPSIntType(resultTy);
7207e3c3ea3SJordy Rose               const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
7217e3c3ea3SJordy Rose               const llvm::APSInt &second = IntType.convert(*RHSValue);
72254569448SJordy Rose 
723fa0734ecSArgyrios Kyrtzidis               const llvm::APSInt *newRHS;
724fa0734ecSArgyrios Kyrtzidis               if (lop == op)
725fa0734ecSArgyrios Kyrtzidis                 newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
726fa0734ecSArgyrios Kyrtzidis               else
727fa0734ecSArgyrios Kyrtzidis                 newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
72854569448SJordy Rose 
72954569448SJordy Rose               assert(newRHS && "Invalid operation despite common type!");
73054569448SJordy Rose               rhs = nonloc::ConcreteInt(*newRHS);
73154569448SJordy Rose               lhs = nonloc::SymbolVal(symIntExpr->getLHS());
73254569448SJordy Rose               op = lop;
73354569448SJordy Rose               continue;
734fa0734ecSArgyrios Kyrtzidis             }
735fa0734ecSArgyrios Kyrtzidis           }
736fa0734ecSArgyrios Kyrtzidis 
73754569448SJordy Rose           // Otherwise, make a SymIntExpr out of the expression.
73854569448SJordy Rose           return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
73954569448SJordy Rose         }
7403b4c3ea2SJordan Rose       }
741fa0734ecSArgyrios Kyrtzidis 
7423b4c3ea2SJordan Rose       // Does the symbolic expression simplify to a constant?
7433b4c3ea2SJordan Rose       // If so, "fold" the constant by setting 'lhs' to a ConcreteInt
7443b4c3ea2SJordan Rose       // and try again.
74512294f8dSArtem Dergachev       SVal simplifiedLhs = simplifySVal(state, lhs);
74612294f8dSArtem Dergachev       if (simplifiedLhs != lhs)
74712294f8dSArtem Dergachev         if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>()) {
74812294f8dSArtem Dergachev           lhs = *simplifiedLhsAsNonLoc;
749fa0734ecSArgyrios Kyrtzidis           continue;
750fa0734ecSArgyrios Kyrtzidis         }
751fa0734ecSArgyrios Kyrtzidis 
75254569448SJordy Rose       // Is the RHS a constant?
75354569448SJordy Rose       if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
75454569448SJordy Rose         return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
755fa0734ecSArgyrios Kyrtzidis 
7562bbccca9SAdam Balogh       if (Optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy))
7572bbccca9SAdam Balogh         return *V;
7582bbccca9SAdam Balogh 
75954569448SJordy Rose       // Give up -- this is not a symbolic expression we can handle.
760*bd3e5dbfSGeorge Karpenkov       return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
761fa0734ecSArgyrios Kyrtzidis     }
762fa0734ecSArgyrios Kyrtzidis     }
763fa0734ecSArgyrios Kyrtzidis   }
764fa0734ecSArgyrios Kyrtzidis }
765fa0734ecSArgyrios Kyrtzidis 
766bac964e1SAnna Zaks static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR,
767bac964e1SAnna Zaks                                             const FieldRegion *RightFR,
768bac964e1SAnna Zaks                                             BinaryOperator::Opcode op,
769bac964e1SAnna Zaks                                             QualType resultTy,
770bac964e1SAnna Zaks                                             SimpleSValBuilder &SVB) {
771bac964e1SAnna Zaks   // Only comparisons are meaningful here!
772bac964e1SAnna Zaks   if (!BinaryOperator::isComparisonOp(op))
773bac964e1SAnna Zaks     return UnknownVal();
774bac964e1SAnna Zaks 
775bac964e1SAnna Zaks   // Next, see if the two FRs have the same super-region.
776bac964e1SAnna Zaks   // FIXME: This doesn't handle casts yet, and simply stripping the casts
777bac964e1SAnna Zaks   // doesn't help.
778bac964e1SAnna Zaks   if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
779bac964e1SAnna Zaks     return UnknownVal();
780bac964e1SAnna Zaks 
781bac964e1SAnna Zaks   const FieldDecl *LeftFD = LeftFR->getDecl();
782bac964e1SAnna Zaks   const FieldDecl *RightFD = RightFR->getDecl();
783bac964e1SAnna Zaks   const RecordDecl *RD = LeftFD->getParent();
784bac964e1SAnna Zaks 
785bac964e1SAnna Zaks   // Make sure the two FRs are from the same kind of record. Just in case!
786bac964e1SAnna Zaks   // FIXME: This is probably where inheritance would be a problem.
787bac964e1SAnna Zaks   if (RD != RightFD->getParent())
788bac964e1SAnna Zaks     return UnknownVal();
789bac964e1SAnna Zaks 
790bac964e1SAnna Zaks   // We know for sure that the two fields are not the same, since that
791bac964e1SAnna Zaks   // would have given us the same SVal.
792bac964e1SAnna Zaks   if (op == BO_EQ)
793bac964e1SAnna Zaks     return SVB.makeTruthVal(false, resultTy);
794bac964e1SAnna Zaks   if (op == BO_NE)
795bac964e1SAnna Zaks     return SVB.makeTruthVal(true, resultTy);
796bac964e1SAnna Zaks 
797bac964e1SAnna Zaks   // Iterate through the fields and see which one comes first.
798bac964e1SAnna Zaks   // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
799bac964e1SAnna Zaks   // members and the units in which bit-fields reside have addresses that
800bac964e1SAnna Zaks   // increase in the order in which they are declared."
801bac964e1SAnna Zaks   bool leftFirst = (op == BO_LT || op == BO_LE);
802e8a8baefSAaron Ballman   for (const auto *I : RD->fields()) {
803e8a8baefSAaron Ballman     if (I == LeftFD)
804bac964e1SAnna Zaks       return SVB.makeTruthVal(leftFirst, resultTy);
805e8a8baefSAaron Ballman     if (I == RightFD)
806bac964e1SAnna Zaks       return SVB.makeTruthVal(!leftFirst, resultTy);
807bac964e1SAnna Zaks   }
808bac964e1SAnna Zaks 
809bac964e1SAnna Zaks   llvm_unreachable("Fields not found in parent record's definition");
810bac964e1SAnna Zaks }
811bac964e1SAnna Zaks 
812fa0734ecSArgyrios Kyrtzidis // FIXME: all this logic will change if/when we have MemRegion::getLocation().
81349b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
814fa0734ecSArgyrios Kyrtzidis                                   BinaryOperator::Opcode op,
815fa0734ecSArgyrios Kyrtzidis                                   Loc lhs, Loc rhs,
816fa0734ecSArgyrios Kyrtzidis                                   QualType resultTy) {
817fa0734ecSArgyrios Kyrtzidis   // Only comparisons and subtractions are valid operations on two pointers.
818fa0734ecSArgyrios Kyrtzidis   // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
819fa0734ecSArgyrios Kyrtzidis   // However, if a pointer is casted to an integer, evalBinOpNN may end up
820fa0734ecSArgyrios Kyrtzidis   // calling this function with another operation (PR7527). We don't attempt to
821fa0734ecSArgyrios Kyrtzidis   // model this for now, but it could be useful, particularly when the
822fa0734ecSArgyrios Kyrtzidis   // "location" is actually an integer value that's been passed through a void*.
823fa0734ecSArgyrios Kyrtzidis   if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
824fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
825fa0734ecSArgyrios Kyrtzidis 
826fa0734ecSArgyrios Kyrtzidis   // Special cases for when both sides are identical.
827fa0734ecSArgyrios Kyrtzidis   if (lhs == rhs) {
828fa0734ecSArgyrios Kyrtzidis     switch (op) {
829fa0734ecSArgyrios Kyrtzidis     default:
83083d382b1SDavid Blaikie       llvm_unreachable("Unimplemented operation for two identical values");
831fa0734ecSArgyrios Kyrtzidis     case BO_Sub:
832fa0734ecSArgyrios Kyrtzidis       return makeZeroVal(resultTy);
833fa0734ecSArgyrios Kyrtzidis     case BO_EQ:
834fa0734ecSArgyrios Kyrtzidis     case BO_LE:
835fa0734ecSArgyrios Kyrtzidis     case BO_GE:
836fa0734ecSArgyrios Kyrtzidis       return makeTruthVal(true, resultTy);
837fa0734ecSArgyrios Kyrtzidis     case BO_NE:
838fa0734ecSArgyrios Kyrtzidis     case BO_LT:
839fa0734ecSArgyrios Kyrtzidis     case BO_GT:
840fa0734ecSArgyrios Kyrtzidis       return makeTruthVal(false, resultTy);
841fa0734ecSArgyrios Kyrtzidis     }
842fa0734ecSArgyrios Kyrtzidis   }
843fa0734ecSArgyrios Kyrtzidis 
844fa0734ecSArgyrios Kyrtzidis   switch (lhs.getSubKind()) {
845fa0734ecSArgyrios Kyrtzidis   default:
84683d382b1SDavid Blaikie     llvm_unreachable("Ordering not implemented for this Loc.");
847fa0734ecSArgyrios Kyrtzidis 
848fa0734ecSArgyrios Kyrtzidis   case loc::GotoLabelKind:
849fa0734ecSArgyrios Kyrtzidis     // The only thing we know about labels is that they're non-null.
850fa0734ecSArgyrios Kyrtzidis     if (rhs.isZeroConstant()) {
851fa0734ecSArgyrios Kyrtzidis       switch (op) {
852fa0734ecSArgyrios Kyrtzidis       default:
853fa0734ecSArgyrios Kyrtzidis         break;
854fa0734ecSArgyrios Kyrtzidis       case BO_Sub:
8555ad574c0SZhanyong Wan         return evalCastFromLoc(lhs, resultTy);
856fa0734ecSArgyrios Kyrtzidis       case BO_EQ:
857fa0734ecSArgyrios Kyrtzidis       case BO_LE:
858fa0734ecSArgyrios Kyrtzidis       case BO_LT:
859fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(false, resultTy);
860fa0734ecSArgyrios Kyrtzidis       case BO_NE:
861fa0734ecSArgyrios Kyrtzidis       case BO_GT:
862fa0734ecSArgyrios Kyrtzidis       case BO_GE:
863fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(true, resultTy);
864fa0734ecSArgyrios Kyrtzidis       }
865fa0734ecSArgyrios Kyrtzidis     }
866fa0734ecSArgyrios Kyrtzidis     // There may be two labels for the same location, and a function region may
867fa0734ecSArgyrios Kyrtzidis     // have the same address as a label at the start of the function (depending
868fa0734ecSArgyrios Kyrtzidis     // on the ABI).
869fa0734ecSArgyrios Kyrtzidis     // FIXME: we can probably do a comparison against other MemRegions, though.
870fa0734ecSArgyrios Kyrtzidis     // FIXME: is there a way to tell if two labels refer to the same location?
871fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
872fa0734ecSArgyrios Kyrtzidis 
873fa0734ecSArgyrios Kyrtzidis   case loc::ConcreteIntKind: {
874fa0734ecSArgyrios Kyrtzidis     // If one of the operands is a symbol and the other is a constant,
875fa0734ecSArgyrios Kyrtzidis     // build an expression for use by the constraint manager.
876fa0734ecSArgyrios Kyrtzidis     if (SymbolRef rSym = rhs.getAsLocSymbol()) {
877c0402c69SDominic Chen       // We can only build expressions with symbols on the left,
878c0402c69SDominic Chen       // so we need a reversible operator.
879c70f1d63SRichard Smith       if (!BinaryOperator::isComparisonOp(op) || op == BO_Cmp)
880c0402c69SDominic Chen         return UnknownVal();
88135610d21SDominic Chen 
882c0402c69SDominic Chen       const llvm::APSInt &lVal = lhs.castAs<loc::ConcreteInt>().getValue();
883604d0bbbSJordan Rose       op = BinaryOperator::reverseComparisonOp(op);
884604d0bbbSJordan Rose       return makeNonLoc(rSym, op, lVal, resultTy);
885fa0734ecSArgyrios Kyrtzidis     }
886fa0734ecSArgyrios Kyrtzidis 
887fa0734ecSArgyrios Kyrtzidis     // If both operands are constants, just perform the operation.
88805785d16SDavid Blaikie     if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
8892fdacbc5SDavid Blaikie       SVal ResultVal =
8902fdacbc5SDavid Blaikie           lhs.castAs<loc::ConcreteInt>().evalBinOp(BasicVals, op, *rInt);
8918eca04b2SJordan Rose       if (Optional<NonLoc> Result = ResultVal.getAs<NonLoc>())
8928eca04b2SJordan Rose         return evalCastFromNonLoc(*Result, resultTy);
8938eca04b2SJordan Rose 
8948eca04b2SJordan Rose       assert(!ResultVal.getAs<Loc>() && "Loc-Loc ops should not produce Locs");
895fa0734ecSArgyrios Kyrtzidis       return UnknownVal();
896fa0734ecSArgyrios Kyrtzidis     }
897fa0734ecSArgyrios Kyrtzidis 
898fa0734ecSArgyrios Kyrtzidis     // Special case comparisons against NULL.
899fa0734ecSArgyrios Kyrtzidis     // This must come after the test if the RHS is a symbol, which is used to
900fa0734ecSArgyrios Kyrtzidis     // build constraints. The address of any non-symbolic region is guaranteed
901fa0734ecSArgyrios Kyrtzidis     // to be non-NULL, as is any label.
9022fdacbc5SDavid Blaikie     assert(rhs.getAs<loc::MemRegionVal>() || rhs.getAs<loc::GotoLabel>());
903fa0734ecSArgyrios Kyrtzidis     if (lhs.isZeroConstant()) {
904fa0734ecSArgyrios Kyrtzidis       switch (op) {
905fa0734ecSArgyrios Kyrtzidis       default:
906fa0734ecSArgyrios Kyrtzidis         break;
907fa0734ecSArgyrios Kyrtzidis       case BO_EQ:
908fa0734ecSArgyrios Kyrtzidis       case BO_GT:
909fa0734ecSArgyrios Kyrtzidis       case BO_GE:
910fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(false, resultTy);
911fa0734ecSArgyrios Kyrtzidis       case BO_NE:
912fa0734ecSArgyrios Kyrtzidis       case BO_LT:
913fa0734ecSArgyrios Kyrtzidis       case BO_LE:
914fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(true, resultTy);
915fa0734ecSArgyrios Kyrtzidis       }
916fa0734ecSArgyrios Kyrtzidis     }
917fa0734ecSArgyrios Kyrtzidis 
918fa0734ecSArgyrios Kyrtzidis     // Comparing an arbitrary integer to a region or label address is
919fa0734ecSArgyrios Kyrtzidis     // completely unknowable.
920fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
921fa0734ecSArgyrios Kyrtzidis   }
92273f018e3SArtem Dergachev   case loc::MemRegionValKind: {
92305785d16SDavid Blaikie     if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
924fa0734ecSArgyrios Kyrtzidis       // If one of the operands is a symbol and the other is a constant,
925fa0734ecSArgyrios Kyrtzidis       // build an expression for use by the constraint manager.
926f4963ff1SAlexander Shaposhnikov       if (SymbolRef lSym = lhs.getAsLocSymbol(true)) {
927f4963ff1SAlexander Shaposhnikov         if (BinaryOperator::isComparisonOp(op))
928fa0734ecSArgyrios Kyrtzidis           return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
929f4963ff1SAlexander Shaposhnikov         return UnknownVal();
930f4963ff1SAlexander Shaposhnikov       }
931fa0734ecSArgyrios Kyrtzidis       // Special case comparisons to NULL.
932fa0734ecSArgyrios Kyrtzidis       // This must come after the test if the LHS is a symbol, which is used to
933fa0734ecSArgyrios Kyrtzidis       // build constraints. The address of any non-symbolic region is guaranteed
934fa0734ecSArgyrios Kyrtzidis       // to be non-NULL.
935fa0734ecSArgyrios Kyrtzidis       if (rInt->isZeroConstant()) {
936acd080b9SJordan Rose         if (op == BO_Sub)
9375ad574c0SZhanyong Wan           return evalCastFromLoc(lhs, resultTy);
938acd080b9SJordan Rose 
939acd080b9SJordan Rose         if (BinaryOperator::isComparisonOp(op)) {
940acd080b9SJordan Rose           QualType boolType = getContext().BoolTy;
941acd080b9SJordan Rose           NonLoc l = evalCastFromLoc(lhs, boolType).castAs<NonLoc>();
942acd080b9SJordan Rose           NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>();
943acd080b9SJordan Rose           return evalBinOpNN(state, op, l, r, resultTy);
944fa0734ecSArgyrios Kyrtzidis         }
945fa0734ecSArgyrios Kyrtzidis       }
946fa0734ecSArgyrios Kyrtzidis 
947fa0734ecSArgyrios Kyrtzidis       // Comparing a region to an arbitrary integer is completely unknowable.
948fa0734ecSArgyrios Kyrtzidis       return UnknownVal();
949fa0734ecSArgyrios Kyrtzidis     }
950fa0734ecSArgyrios Kyrtzidis 
951fa0734ecSArgyrios Kyrtzidis     // Get both values as regions, if possible.
952fa0734ecSArgyrios Kyrtzidis     const MemRegion *LeftMR = lhs.getAsRegion();
95373f018e3SArtem Dergachev     assert(LeftMR && "MemRegionValKind SVal doesn't have a region!");
954fa0734ecSArgyrios Kyrtzidis 
955fa0734ecSArgyrios Kyrtzidis     const MemRegion *RightMR = rhs.getAsRegion();
956fa0734ecSArgyrios Kyrtzidis     if (!RightMR)
957fa0734ecSArgyrios Kyrtzidis       // The RHS is probably a label, which in theory could address a region.
958fa0734ecSArgyrios Kyrtzidis       // FIXME: we can probably make a more useful statement about non-code
959fa0734ecSArgyrios Kyrtzidis       // regions, though.
960fa0734ecSArgyrios Kyrtzidis       return UnknownVal();
961fa0734ecSArgyrios Kyrtzidis 
962fa0734ecSArgyrios Kyrtzidis     const MemRegion *LeftBase = LeftMR->getBaseRegion();
963fa0734ecSArgyrios Kyrtzidis     const MemRegion *RightBase = RightMR->getBaseRegion();
9643b4c3ea2SJordan Rose     const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
9653b4c3ea2SJordan Rose     const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
9663b4c3ea2SJordan Rose     const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
9673563fde6SAnna Zaks 
9683563fde6SAnna Zaks     // If the two regions are from different known memory spaces they cannot be
9693563fde6SAnna Zaks     // equal. Also, assume that no symbolic region (whose memory space is
9703563fde6SAnna Zaks     // unknown) is on the stack.
9713563fde6SAnna Zaks     if (LeftMS != RightMS &&
9723563fde6SAnna Zaks         ((LeftMS != UnknownMS && RightMS != UnknownMS) ||
9733563fde6SAnna Zaks          (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
974fa0734ecSArgyrios Kyrtzidis       switch (op) {
975fa0734ecSArgyrios Kyrtzidis       default:
976fa0734ecSArgyrios Kyrtzidis         return UnknownVal();
977fa0734ecSArgyrios Kyrtzidis       case BO_EQ:
978fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(false, resultTy);
979fa0734ecSArgyrios Kyrtzidis       case BO_NE:
980fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(true, resultTy);
981fa0734ecSArgyrios Kyrtzidis       }
982fa0734ecSArgyrios Kyrtzidis     }
983fa0734ecSArgyrios Kyrtzidis 
9843563fde6SAnna Zaks     // If both values wrap regions, see if they're from different base regions.
9853563fde6SAnna Zaks     // Note, heap base symbolic regions are assumed to not alias with
9863563fde6SAnna Zaks     // each other; for example, we assume that malloc returns different address
9873563fde6SAnna Zaks     // on each invocation.
988aacc03c9SArtem Dergachev     // FIXME: ObjC object pointers always reside on the heap, but currently
989aacc03c9SArtem Dergachev     // we treat their memory space as unknown, because symbolic pointers
990aacc03c9SArtem Dergachev     // to ObjC objects may alias. There should be a way to construct
991aacc03c9SArtem Dergachev     // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker
992aacc03c9SArtem Dergachev     // guesses memory space for ObjC object pointers manually instead of
993aacc03c9SArtem Dergachev     // relying on us.
9943563fde6SAnna Zaks     if (LeftBase != RightBase &&
9953563fde6SAnna Zaks         ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
996a7dcc996SAnna Zaks          (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
9979d96f843STed Kremenek       switch (op) {
9989d96f843STed Kremenek       default:
9993563fde6SAnna Zaks         return UnknownVal();
10009d96f843STed Kremenek       case BO_EQ:
10019d96f843STed Kremenek         return makeTruthVal(false, resultTy);
10029d96f843STed Kremenek       case BO_NE:
10039d96f843STed Kremenek         return makeTruthVal(true, resultTy);
10049d96f843STed Kremenek       }
10059d96f843STed Kremenek     }
1006fa0734ecSArgyrios Kyrtzidis 
1007bac964e1SAnna Zaks     // Handle special cases for when both regions are element regions.
1008fa0734ecSArgyrios Kyrtzidis     const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
1009bac964e1SAnna Zaks     const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR);
1010bac964e1SAnna Zaks     if (RightER && LeftER) {
1011fa0734ecSArgyrios Kyrtzidis       // Next, see if the two ERs have the same super-region and matching types.
1012fa0734ecSArgyrios Kyrtzidis       // FIXME: This should do something useful even if the types don't match,
1013fa0734ecSArgyrios Kyrtzidis       // though if both indexes are constant the RegionRawOffset path will
1014fa0734ecSArgyrios Kyrtzidis       // give the correct answer.
1015fa0734ecSArgyrios Kyrtzidis       if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
1016fa0734ecSArgyrios Kyrtzidis           LeftER->getElementType() == RightER->getElementType()) {
1017fa0734ecSArgyrios Kyrtzidis         // Get the left index and cast it to the correct type.
1018fa0734ecSArgyrios Kyrtzidis         // If the index is unknown or undefined, bail out here.
1019fa0734ecSArgyrios Kyrtzidis         SVal LeftIndexVal = LeftER->getIndex();
102005785d16SDavid Blaikie         Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
1021fa0734ecSArgyrios Kyrtzidis         if (!LeftIndex)
1022fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
10232317f30fSTed Kremenek         LeftIndexVal = evalCastFromNonLoc(*LeftIndex, ArrayIndexTy);
10242fdacbc5SDavid Blaikie         LeftIndex = LeftIndexVal.getAs<NonLoc>();
1025fa0734ecSArgyrios Kyrtzidis         if (!LeftIndex)
1026fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
1027fa0734ecSArgyrios Kyrtzidis 
1028fa0734ecSArgyrios Kyrtzidis         // Do the same for the right index.
1029fa0734ecSArgyrios Kyrtzidis         SVal RightIndexVal = RightER->getIndex();
103005785d16SDavid Blaikie         Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
1031fa0734ecSArgyrios Kyrtzidis         if (!RightIndex)
1032fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
10332317f30fSTed Kremenek         RightIndexVal = evalCastFromNonLoc(*RightIndex, ArrayIndexTy);
10342fdacbc5SDavid Blaikie         RightIndex = RightIndexVal.getAs<NonLoc>();
1035fa0734ecSArgyrios Kyrtzidis         if (!RightIndex)
1036fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
1037fa0734ecSArgyrios Kyrtzidis 
1038fa0734ecSArgyrios Kyrtzidis         // Actually perform the operation.
1039fa0734ecSArgyrios Kyrtzidis         // evalBinOpNN expects the two indexes to already be the right type.
1040fa0734ecSArgyrios Kyrtzidis         return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
1041fa0734ecSArgyrios Kyrtzidis       }
1042bac964e1SAnna Zaks     }
1043fa0734ecSArgyrios Kyrtzidis 
1044bac964e1SAnna Zaks     // Special handling of the FieldRegions, even with symbolic offsets.
1045bac964e1SAnna Zaks     const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
1046bac964e1SAnna Zaks     const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR);
1047bac964e1SAnna Zaks     if (RightFR && LeftFR) {
1048bac964e1SAnna Zaks       SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy,
1049bac964e1SAnna Zaks                                                *this);
1050bac964e1SAnna Zaks       if (!R.isUnknown())
1051bac964e1SAnna Zaks         return R;
1052bac964e1SAnna Zaks     }
1053bac964e1SAnna Zaks 
1054bac964e1SAnna Zaks     // Compare the regions using the raw offsets.
1055bac964e1SAnna Zaks     RegionOffset LeftOffset = LeftMR->getAsOffset();
1056bac964e1SAnna Zaks     RegionOffset RightOffset = RightMR->getAsOffset();
1057fa0734ecSArgyrios Kyrtzidis 
10580dbb783cSCraig Topper     if (LeftOffset.getRegion() != nullptr &&
1059bac964e1SAnna Zaks         LeftOffset.getRegion() == RightOffset.getRegion() &&
1060bac964e1SAnna Zaks         !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) {
1061bac964e1SAnna Zaks       int64_t left = LeftOffset.getOffset();
1062bac964e1SAnna Zaks       int64_t right = RightOffset.getOffset();
1063fa0734ecSArgyrios Kyrtzidis 
1064fa0734ecSArgyrios Kyrtzidis       switch (op) {
1065fa0734ecSArgyrios Kyrtzidis         default:
1066fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
1067fa0734ecSArgyrios Kyrtzidis         case BO_LT:
1068fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left < right, resultTy);
1069fa0734ecSArgyrios Kyrtzidis         case BO_GT:
1070fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left > right, resultTy);
1071fa0734ecSArgyrios Kyrtzidis         case BO_LE:
1072fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left <= right, resultTy);
1073fa0734ecSArgyrios Kyrtzidis         case BO_GE:
1074fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left >= right, resultTy);
1075fa0734ecSArgyrios Kyrtzidis         case BO_EQ:
1076fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left == right, resultTy);
1077fa0734ecSArgyrios Kyrtzidis         case BO_NE:
1078fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left != right, resultTy);
1079fa0734ecSArgyrios Kyrtzidis       }
1080fa0734ecSArgyrios Kyrtzidis     }
1081fa0734ecSArgyrios Kyrtzidis 
10823b4c3ea2SJordan Rose     // At this point we're not going to get a good answer, but we can try
10833b4c3ea2SJordan Rose     // conjuring an expression instead.
10843b4c3ea2SJordan Rose     SymbolRef LHSSym = lhs.getAsLocSymbol();
10853b4c3ea2SJordan Rose     SymbolRef RHSSym = rhs.getAsLocSymbol();
10863b4c3ea2SJordan Rose     if (LHSSym && RHSSym)
10873b4c3ea2SJordan Rose       return makeNonLoc(LHSSym, op, RHSSym, resultTy);
10883b4c3ea2SJordan Rose 
1089fa0734ecSArgyrios Kyrtzidis     // If we get here, we have no way of comparing the regions.
1090fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
1091fa0734ecSArgyrios Kyrtzidis   }
1092fa0734ecSArgyrios Kyrtzidis   }
1093fa0734ecSArgyrios Kyrtzidis }
1094fa0734ecSArgyrios Kyrtzidis 
109549b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
1096fa0734ecSArgyrios Kyrtzidis                                   BinaryOperator::Opcode op,
1097fa0734ecSArgyrios Kyrtzidis                                   Loc lhs, NonLoc rhs, QualType resultTy) {
109864c01f7bSDevin Coughlin   if (op >= BO_PtrMemD && op <= BO_PtrMemI) {
109964c01f7bSDevin Coughlin     if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) {
110064c01f7bSDevin Coughlin       if (PTMSV->isNullMemberPointer())
110164c01f7bSDevin Coughlin         return UndefinedVal();
110264c01f7bSDevin Coughlin       if (const FieldDecl *FD = PTMSV->getDeclAs<FieldDecl>()) {
110364c01f7bSDevin Coughlin         SVal Result = lhs;
110464c01f7bSDevin Coughlin 
110564c01f7bSDevin Coughlin         for (const auto &I : *PTMSV)
110664c01f7bSDevin Coughlin           Result = StateMgr.getStoreManager().evalDerivedToBase(
110764c01f7bSDevin Coughlin               Result, I->getType(),I->isVirtual());
110864c01f7bSDevin Coughlin         return state->getLValue(FD, Result);
110964c01f7bSDevin Coughlin       }
111064c01f7bSDevin Coughlin     }
111164c01f7bSDevin Coughlin 
111264c01f7bSDevin Coughlin     return rhs;
111364c01f7bSDevin Coughlin   }
111464c01f7bSDevin Coughlin 
1115686df322SJordan Rose   assert(!BinaryOperator::isComparisonOp(op) &&
1116686df322SJordan Rose          "arguments to comparison ops must be of the same type");
1117fa0734ecSArgyrios Kyrtzidis 
1118fa0734ecSArgyrios Kyrtzidis   // Special case: rhs is a zero constant.
1119fa0734ecSArgyrios Kyrtzidis   if (rhs.isZeroConstant())
1120fa0734ecSArgyrios Kyrtzidis     return lhs;
1121fa0734ecSArgyrios Kyrtzidis 
112221524676SGabor Horvath   // Perserve the null pointer so that it can be found by the DerefChecker.
112321524676SGabor Horvath   if (lhs.isZeroConstant())
112421524676SGabor Horvath     return lhs;
112521524676SGabor Horvath 
1126fa0734ecSArgyrios Kyrtzidis   // We are dealing with pointer arithmetic.
1127fa0734ecSArgyrios Kyrtzidis 
1128fa0734ecSArgyrios Kyrtzidis   // Handle pointer arithmetic on constant values.
112905785d16SDavid Blaikie   if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) {
113005785d16SDavid Blaikie     if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) {
1131fa0734ecSArgyrios Kyrtzidis       const llvm::APSInt &leftI = lhsInt->getValue();
1132fa0734ecSArgyrios Kyrtzidis       assert(leftI.isUnsigned());
1133fa0734ecSArgyrios Kyrtzidis       llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
1134fa0734ecSArgyrios Kyrtzidis 
1135fa0734ecSArgyrios Kyrtzidis       // Convert the bitwidth of rightI.  This should deal with overflow
1136fa0734ecSArgyrios Kyrtzidis       // since we are dealing with concrete values.
1137fa0734ecSArgyrios Kyrtzidis       rightI = rightI.extOrTrunc(leftI.getBitWidth());
1138fa0734ecSArgyrios Kyrtzidis 
1139fa0734ecSArgyrios Kyrtzidis       // Offset the increment by the pointer size.
1140fa0734ecSArgyrios Kyrtzidis       llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
114121524676SGabor Horvath       QualType pointeeType = resultTy->getPointeeType();
114221524676SGabor Horvath       Multiplicand = getContext().getTypeSizeInChars(pointeeType).getQuantity();
1143fa0734ecSArgyrios Kyrtzidis       rightI *= Multiplicand;
1144fa0734ecSArgyrios Kyrtzidis 
1145fa0734ecSArgyrios Kyrtzidis       // Compute the adjusted pointer.
1146fa0734ecSArgyrios Kyrtzidis       switch (op) {
1147fa0734ecSArgyrios Kyrtzidis         case BO_Add:
1148fa0734ecSArgyrios Kyrtzidis           rightI = leftI + rightI;
1149fa0734ecSArgyrios Kyrtzidis           break;
1150fa0734ecSArgyrios Kyrtzidis         case BO_Sub:
1151fa0734ecSArgyrios Kyrtzidis           rightI = leftI - rightI;
1152fa0734ecSArgyrios Kyrtzidis           break;
1153fa0734ecSArgyrios Kyrtzidis         default:
1154fa0734ecSArgyrios Kyrtzidis           llvm_unreachable("Invalid pointer arithmetic operation");
1155fa0734ecSArgyrios Kyrtzidis       }
1156fa0734ecSArgyrios Kyrtzidis       return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
1157fa0734ecSArgyrios Kyrtzidis     }
1158fa0734ecSArgyrios Kyrtzidis   }
1159fa0734ecSArgyrios Kyrtzidis 
1160fa0734ecSArgyrios Kyrtzidis   // Handle cases where 'lhs' is a region.
1161fa0734ecSArgyrios Kyrtzidis   if (const MemRegion *region = lhs.getAsRegion()) {
11622fdacbc5SDavid Blaikie     rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
1163fa0734ecSArgyrios Kyrtzidis     SVal index = UnknownVal();
11646dd11048SArtem Dergachev     const SubRegion *superR = nullptr;
11657333a9eaSArtem Dergachev     // We need to know the type of the pointer in order to add an integer to it.
11667333a9eaSArtem Dergachev     // Depending on the type, different amount of bytes is added.
1167fa0734ecSArgyrios Kyrtzidis     QualType elementType;
1168fa0734ecSArgyrios Kyrtzidis 
1169fa0734ecSArgyrios Kyrtzidis     if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
117057a4a152STed Kremenek       assert(op == BO_Add || op == BO_Sub);
117157a4a152STed Kremenek       index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
1172fa0734ecSArgyrios Kyrtzidis                           getArrayIndexType());
11736dd11048SArtem Dergachev       superR = cast<SubRegion>(elemReg->getSuperRegion());
1174fa0734ecSArgyrios Kyrtzidis       elementType = elemReg->getElementType();
1175fa0734ecSArgyrios Kyrtzidis     }
1176fa0734ecSArgyrios Kyrtzidis     else if (isa<SubRegion>(region)) {
1177c4b28a8fSGabor Horvath       assert(op == BO_Add || op == BO_Sub);
1178c4b28a8fSGabor Horvath       index = (op == BO_Add) ? rhs : evalMinus(rhs);
11796dd11048SArtem Dergachev       superR = cast<SubRegion>(region);
11807333a9eaSArtem Dergachev       // TODO: Is this actually reliable? Maybe improving our MemRegion
11817333a9eaSArtem Dergachev       // hierarchy to provide typed regions for all non-void pointers would be
11827333a9eaSArtem Dergachev       // better. For instance, we cannot extend this towards LocAsInteger
11837333a9eaSArtem Dergachev       // operations, where result type of the expression is integer.
1184d1a08b6eSJordan Rose       if (resultTy->isAnyPointerType())
1185d1a08b6eSJordan Rose         elementType = resultTy->getPointeeType();
1186fa0734ecSArgyrios Kyrtzidis     }
1187fa0734ecSArgyrios Kyrtzidis 
1188df1bb8a6SArtem Dergachev     // Represent arithmetic on void pointers as arithmetic on char pointers.
1189df1bb8a6SArtem Dergachev     // It is fine when a TypedValueRegion of char value type represents
1190df1bb8a6SArtem Dergachev     // a void pointer. Note that arithmetic on void pointers is a GCC extension.
1191df1bb8a6SArtem Dergachev     if (elementType->isVoidType())
1192df1bb8a6SArtem Dergachev       elementType = getContext().CharTy;
1193df1bb8a6SArtem Dergachev 
119405785d16SDavid Blaikie     if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) {
1195fa0734ecSArgyrios Kyrtzidis       return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
1196fa0734ecSArgyrios Kyrtzidis                                                        superR, getContext()));
1197fa0734ecSArgyrios Kyrtzidis     }
1198fa0734ecSArgyrios Kyrtzidis   }
1199fa0734ecSArgyrios Kyrtzidis   return UnknownVal();
1200fa0734ecSArgyrios Kyrtzidis }
1201fa0734ecSArgyrios Kyrtzidis 
120249b1e38eSTed Kremenek const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
1203fa0734ecSArgyrios Kyrtzidis                                                    SVal V) {
1204fa0734ecSArgyrios Kyrtzidis   if (V.isUnknownOrUndef())
12050dbb783cSCraig Topper     return nullptr;
1206fa0734ecSArgyrios Kyrtzidis 
120705785d16SDavid Blaikie   if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
1208fa0734ecSArgyrios Kyrtzidis     return &X->getValue();
1209fa0734ecSArgyrios Kyrtzidis 
121005785d16SDavid Blaikie   if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
1211fa0734ecSArgyrios Kyrtzidis     return &X->getValue();
1212fa0734ecSArgyrios Kyrtzidis 
1213fa0734ecSArgyrios Kyrtzidis   if (SymbolRef Sym = V.getAsSymbol())
1214244e1d7dSTed Kremenek     return state->getConstraintManager().getSymVal(state, Sym);
1215fa0734ecSArgyrios Kyrtzidis 
1216c0402c69SDominic Chen   // FIXME: Add support for SymExprs.
12170dbb783cSCraig Topper   return nullptr;
1218fa0734ecSArgyrios Kyrtzidis }
121912294f8dSArtem Dergachev 
122012294f8dSArtem Dergachev SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) {
122112294f8dSArtem Dergachev   // For now, this function tries to constant-fold symbols inside a
122212294f8dSArtem Dergachev   // nonloc::SymbolVal, and does nothing else. More simplifications should
122312294f8dSArtem Dergachev   // be possible, such as constant-folding an index in an ElementRegion.
122412294f8dSArtem Dergachev 
122512294f8dSArtem Dergachev   class Simplifier : public FullSValVisitor<Simplifier, SVal> {
122612294f8dSArtem Dergachev     ProgramStateRef State;
122712294f8dSArtem Dergachev     SValBuilder &SVB;
122812294f8dSArtem Dergachev 
122922746d7dSArtem Dergachev     // Cache results for the lifetime of the Simplifier. Results change every
123022746d7dSArtem Dergachev     // time new constraints are added to the program state, which is the whole
123122746d7dSArtem Dergachev     // point of simplifying, and for that very reason it's pointless to maintain
123222746d7dSArtem Dergachev     // the same cache for the duration of the whole analysis.
123322746d7dSArtem Dergachev     llvm::DenseMap<SymbolRef, SVal> Cached;
123422746d7dSArtem Dergachev 
123516a1f64cSArtem Dergachev     static bool isUnchanged(SymbolRef Sym, SVal Val) {
123616a1f64cSArtem Dergachev       return Sym == Val.getAsSymbol();
123716a1f64cSArtem Dergachev     }
123816a1f64cSArtem Dergachev 
12399fe9a95fSArtem Dergachev     SVal cache(SymbolRef Sym, SVal V) {
12409fe9a95fSArtem Dergachev       Cached[Sym] = V;
12419fe9a95fSArtem Dergachev       return V;
12429fe9a95fSArtem Dergachev     }
12439fe9a95fSArtem Dergachev 
12449fe9a95fSArtem Dergachev     SVal skip(SymbolRef Sym) {
12459fe9a95fSArtem Dergachev       return cache(Sym, SVB.makeSymbolVal(Sym));
12469fe9a95fSArtem Dergachev     }
12479fe9a95fSArtem Dergachev 
124812294f8dSArtem Dergachev   public:
124912294f8dSArtem Dergachev     Simplifier(ProgramStateRef State)
125012294f8dSArtem Dergachev         : State(State), SVB(State->getStateManager().getSValBuilder()) {}
125112294f8dSArtem Dergachev 
125212294f8dSArtem Dergachev     SVal VisitSymbolData(const SymbolData *S) {
12539fe9a95fSArtem Dergachev       // No cache here.
125412294f8dSArtem Dergachev       if (const llvm::APSInt *I =
1255d1163790SArtem Dergachev               SVB.getKnownValue(State, SVB.makeSymbolVal(S)))
125612294f8dSArtem Dergachev         return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I)
125712294f8dSArtem Dergachev                                             : (SVal)SVB.makeIntVal(*I);
125816a1f64cSArtem Dergachev       return SVB.makeSymbolVal(S);
125912294f8dSArtem Dergachev     }
126012294f8dSArtem Dergachev 
1261c0402c69SDominic Chen     // TODO: Support SymbolCast. Support IntSymExpr when/if we actually
1262c0402c69SDominic Chen     // start producing them.
126312294f8dSArtem Dergachev 
126412294f8dSArtem Dergachev     SVal VisitSymIntExpr(const SymIntExpr *S) {
126522746d7dSArtem Dergachev       auto I = Cached.find(S);
126622746d7dSArtem Dergachev       if (I != Cached.end())
126722746d7dSArtem Dergachev         return I->second;
126822746d7dSArtem Dergachev 
126912294f8dSArtem Dergachev       SVal LHS = Visit(S->getLHS());
12709fe9a95fSArtem Dergachev       if (isUnchanged(S->getLHS(), LHS))
12719fe9a95fSArtem Dergachev         return skip(S);
12729fe9a95fSArtem Dergachev 
127312294f8dSArtem Dergachev       SVal RHS;
127412294f8dSArtem Dergachev       // By looking at the APSInt in the right-hand side of S, we cannot
127512294f8dSArtem Dergachev       // figure out if it should be treated as a Loc or as a NonLoc.
127612294f8dSArtem Dergachev       // So make our guess by recalling that we cannot multiply pointers
127712294f8dSArtem Dergachev       // or compare a pointer to an integer.
127812294f8dSArtem Dergachev       if (Loc::isLocType(S->getLHS()->getType()) &&
127912294f8dSArtem Dergachev           BinaryOperator::isComparisonOp(S->getOpcode())) {
128012294f8dSArtem Dergachev         // The usual conversion of $sym to &SymRegion{$sym}, as they have
128112294f8dSArtem Dergachev         // the same meaning for Loc-type symbols, but the latter form
128212294f8dSArtem Dergachev         // is preferred in SVal computations for being Loc itself.
128312294f8dSArtem Dergachev         if (SymbolRef Sym = LHS.getAsSymbol()) {
128412294f8dSArtem Dergachev           assert(Loc::isLocType(Sym->getType()));
128512294f8dSArtem Dergachev           LHS = SVB.makeLoc(Sym);
128612294f8dSArtem Dergachev         }
128712294f8dSArtem Dergachev         RHS = SVB.makeIntLocVal(S->getRHS());
128812294f8dSArtem Dergachev       } else {
128912294f8dSArtem Dergachev         RHS = SVB.makeIntVal(S->getRHS());
129012294f8dSArtem Dergachev       }
129122746d7dSArtem Dergachev 
12929fe9a95fSArtem Dergachev       return cache(
12939fe9a95fSArtem Dergachev           S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
129412294f8dSArtem Dergachev     }
129512294f8dSArtem Dergachev 
129612294f8dSArtem Dergachev     SVal VisitSymSymExpr(const SymSymExpr *S) {
129722746d7dSArtem Dergachev       auto I = Cached.find(S);
129822746d7dSArtem Dergachev       if (I != Cached.end())
129922746d7dSArtem Dergachev         return I->second;
130022746d7dSArtem Dergachev 
130105220a90SArtem Dergachev       // For now don't try to simplify mixed Loc/NonLoc expressions
130205220a90SArtem Dergachev       // because they often appear from LocAsInteger operations
130305220a90SArtem Dergachev       // and we don't know how to combine a LocAsInteger
130405220a90SArtem Dergachev       // with a concrete value.
130505220a90SArtem Dergachev       if (Loc::isLocType(S->getLHS()->getType()) !=
13069fe9a95fSArtem Dergachev           Loc::isLocType(S->getRHS()->getType()))
13079fe9a95fSArtem Dergachev         return skip(S);
130805220a90SArtem Dergachev 
130912294f8dSArtem Dergachev       SVal LHS = Visit(S->getLHS());
131012294f8dSArtem Dergachev       SVal RHS = Visit(S->getRHS());
13119fe9a95fSArtem Dergachev       if (isUnchanged(S->getLHS(), LHS) && isUnchanged(S->getRHS(), RHS))
13129fe9a95fSArtem Dergachev         return skip(S);
13139fe9a95fSArtem Dergachev 
13149fe9a95fSArtem Dergachev       return cache(
13159fe9a95fSArtem Dergachev           S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
131612294f8dSArtem Dergachev     }
131712294f8dSArtem Dergachev 
131812294f8dSArtem Dergachev     SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); }
131912294f8dSArtem Dergachev 
132012294f8dSArtem Dergachev     SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); }
132112294f8dSArtem Dergachev 
132212294f8dSArtem Dergachev     SVal VisitNonLocSymbolVal(nonloc::SymbolVal V) {
132312294f8dSArtem Dergachev       // Simplification is much more costly than computing complexity.
132412294f8dSArtem Dergachev       // For high complexity, it may be not worth it.
132512294f8dSArtem Dergachev       return Visit(V.getSymbol());
132612294f8dSArtem Dergachev     }
132712294f8dSArtem Dergachev 
132812294f8dSArtem Dergachev     SVal VisitSVal(SVal V) { return V; }
132912294f8dSArtem Dergachev   };
133012294f8dSArtem Dergachev 
133116a1f64cSArtem Dergachev   // A crude way of preventing this function from calling itself from evalBinOp.
133216a1f64cSArtem Dergachev   static bool isReentering = false;
133316a1f64cSArtem Dergachev   if (isReentering)
133416a1f64cSArtem Dergachev     return V;
133516a1f64cSArtem Dergachev 
133616a1f64cSArtem Dergachev   isReentering = true;
133716a1f64cSArtem Dergachev   SVal SimplifiedV = Simplifier(State).Visit(V);
133816a1f64cSArtem Dergachev   isReentering = false;
133916a1f64cSArtem Dergachev 
134016a1f64cSArtem Dergachev   return SimplifiedV;
134112294f8dSArtem Dergachev }
1342