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"
142bbccca9SAdam Balogh #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
153a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
16001fd5b4STed Kremenek #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
172bbccca9SAdam Balogh #include "clang/StaticAnalyzer/Core/PathSensitive/SubEngine.h"
1812294f8dSArtem Dergachev #include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h"
19fa0734ecSArgyrios Kyrtzidis 
20fa0734ecSArgyrios Kyrtzidis using namespace clang;
21fa0734ecSArgyrios Kyrtzidis using namespace ento;
22fa0734ecSArgyrios Kyrtzidis 
23fa0734ecSArgyrios Kyrtzidis namespace {
24fa0734ecSArgyrios Kyrtzidis class SimpleSValBuilder : public SValBuilder {
25fa0734ecSArgyrios Kyrtzidis protected:
26fb6b25b5SCraig Topper   SVal dispatchCast(SVal val, QualType castTy) override;
27fb6b25b5SCraig Topper   SVal evalCastFromNonLoc(NonLoc val, QualType castTy) override;
28fb6b25b5SCraig Topper   SVal evalCastFromLoc(Loc val, QualType castTy) override;
29fa0734ecSArgyrios Kyrtzidis 
30fa0734ecSArgyrios Kyrtzidis public:
31fa0734ecSArgyrios Kyrtzidis   SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
32001fd5b4STed Kremenek                     ProgramStateManager &stateMgr)
33fa0734ecSArgyrios Kyrtzidis                     : SValBuilder(alloc, context, stateMgr) {}
34637d1e66SAngel Garcia Gomez   ~SimpleSValBuilder() override {}
35fa0734ecSArgyrios Kyrtzidis 
36fb6b25b5SCraig Topper   SVal evalMinus(NonLoc val) override;
37fb6b25b5SCraig Topper   SVal evalComplement(NonLoc val) override;
38fb6b25b5SCraig Topper   SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
39fb6b25b5SCraig Topper                    NonLoc lhs, NonLoc rhs, QualType resultTy) override;
40fb6b25b5SCraig Topper   SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
41fb6b25b5SCraig Topper                    Loc lhs, Loc rhs, QualType resultTy) override;
42fb6b25b5SCraig Topper   SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
43fb6b25b5SCraig Topper                    Loc lhs, NonLoc rhs, QualType resultTy) override;
44fa0734ecSArgyrios Kyrtzidis 
45fa0734ecSArgyrios Kyrtzidis   /// getKnownValue - evaluates a given SVal. If the SVal has only one possible
46fa0734ecSArgyrios Kyrtzidis   ///  (integer) value, that value is returned. Otherwise, returns NULL.
47fb6b25b5SCraig Topper   const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override;
48fa0734ecSArgyrios Kyrtzidis 
4912294f8dSArtem Dergachev   /// Recursively descends into symbolic expressions and replaces symbols
5012294f8dSArtem Dergachev   /// with their known values (in the sense of the getKnownValue() method).
5112294f8dSArtem Dergachev   SVal simplifySVal(ProgramStateRef State, SVal V) override;
5212294f8dSArtem Dergachev 
53fa0734ecSArgyrios Kyrtzidis   SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
54fa0734ecSArgyrios Kyrtzidis                      const llvm::APSInt &RHS, QualType resultTy);
55fa0734ecSArgyrios Kyrtzidis };
56fa0734ecSArgyrios Kyrtzidis } // end anonymous namespace
57fa0734ecSArgyrios Kyrtzidis 
58fa0734ecSArgyrios Kyrtzidis SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
59fa0734ecSArgyrios Kyrtzidis                                            ASTContext &context,
60001fd5b4STed Kremenek                                            ProgramStateManager &stateMgr) {
61fa0734ecSArgyrios Kyrtzidis   return new SimpleSValBuilder(alloc, context, stateMgr);
62fa0734ecSArgyrios Kyrtzidis }
63fa0734ecSArgyrios Kyrtzidis 
64fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
65fa0734ecSArgyrios Kyrtzidis // Transfer function for Casts.
66fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
67fa0734ecSArgyrios Kyrtzidis 
68c95a6c4cSAnna Zaks SVal SimpleSValBuilder::dispatchCast(SVal Val, QualType CastTy) {
692fdacbc5SDavid Blaikie   assert(Val.getAs<Loc>() || Val.getAs<NonLoc>());
702fdacbc5SDavid Blaikie   return Val.getAs<Loc>() ? evalCastFromLoc(Val.castAs<Loc>(), CastTy)
712fdacbc5SDavid Blaikie                            : evalCastFromNonLoc(Val.castAs<NonLoc>(), CastTy);
72c25efcccSAnna Zaks }
73c25efcccSAnna Zaks 
745ad574c0SZhanyong Wan SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
7585a203ebSZhanyong Wan   bool isLocType = Loc::isLocType(castTy);
7664c01f7bSDevin Coughlin   if (val.getAs<nonloc::PointerToMember>())
7764c01f7bSDevin Coughlin     return val;
7864c01f7bSDevin Coughlin 
7905785d16SDavid Blaikie   if (Optional<nonloc::LocAsInteger> LI = val.getAs<nonloc::LocAsInteger>()) {
80fa0734ecSArgyrios Kyrtzidis     if (isLocType)
81fa0734ecSArgyrios Kyrtzidis       return LI->getLoc();
82fa0734ecSArgyrios Kyrtzidis     // FIXME: Correctly support promotions/truncations.
8359d10a4cSAlexander Shaposhnikov     unsigned castSize = Context.getIntWidth(castTy);
84fa0734ecSArgyrios Kyrtzidis     if (castSize == LI->getNumBits())
85fa0734ecSArgyrios Kyrtzidis       return val;
86fa0734ecSArgyrios Kyrtzidis     return makeLocAsInteger(LI->getLoc(), castSize);
87fa0734ecSArgyrios Kyrtzidis   }
88fa0734ecSArgyrios Kyrtzidis 
89fa0734ecSArgyrios Kyrtzidis   if (const SymExpr *se = val.getAsSymbolicExpression()) {
90a808e165STed Kremenek     QualType T = Context.getCanonicalType(se->getType());
916af472aaSAnna Zaks     // If types are the same or both are integers, ignore the cast.
92fa0734ecSArgyrios Kyrtzidis     // FIXME: Remove this hack when we support symbolic truncation/extension.
93fa0734ecSArgyrios Kyrtzidis     // HACK: If both castTy and T are integers, ignore the cast.  This is
94fa0734ecSArgyrios Kyrtzidis     // not a permanent solution.  Eventually we want to precisely handle
95fa0734ecSArgyrios Kyrtzidis     // extension/truncation of symbolic integers.  This prevents us from losing
96fa0734ecSArgyrios Kyrtzidis     // precision when we assign 'x = y' and 'y' is symbolic and x and y are
97fa0734ecSArgyrios Kyrtzidis     // different integer types.
986af472aaSAnna Zaks    if (haveSameType(T, castTy))
99fa0734ecSArgyrios Kyrtzidis       return val;
100fa0734ecSArgyrios Kyrtzidis 
101c25efcccSAnna Zaks     if (!isLocType)
102c25efcccSAnna Zaks       return makeNonLoc(se, T, castTy);
103fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
104fa0734ecSArgyrios Kyrtzidis   }
105fa0734ecSArgyrios Kyrtzidis 
106d4733638SAlp Toker   // If value is a non-integer constant, produce unknown.
1072fdacbc5SDavid Blaikie   if (!val.getAs<nonloc::ConcreteInt>())
108fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
109fa0734ecSArgyrios Kyrtzidis 
1102317f30fSTed Kremenek   // Handle casts to a boolean type.
1112317f30fSTed Kremenek   if (castTy->isBooleanType()) {
1122fdacbc5SDavid Blaikie     bool b = val.castAs<nonloc::ConcreteInt>().getValue().getBoolValue();
1132317f30fSTed Kremenek     return makeTruthVal(b, castTy);
1142317f30fSTed Kremenek   }
1152317f30fSTed Kremenek 
116394256ccSAnna Zaks   // Only handle casts from integers to integers - if val is an integer constant
117d4733638SAlp Toker   // being cast to a non-integer type, produce unknown.
11861e221f6SJordan Rose   if (!isLocType && !castTy->isIntegralOrEnumerationType())
119fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
120fa0734ecSArgyrios Kyrtzidis 
1212fdacbc5SDavid Blaikie   llvm::APSInt i = val.castAs<nonloc::ConcreteInt>().getValue();
1227e3c3ea3SJordy Rose   BasicVals.getAPSIntType(castTy).apply(i);
123fa0734ecSArgyrios Kyrtzidis 
124fa0734ecSArgyrios Kyrtzidis   if (isLocType)
125fa0734ecSArgyrios Kyrtzidis     return makeIntLocVal(i);
126fa0734ecSArgyrios Kyrtzidis   else
127fa0734ecSArgyrios Kyrtzidis     return makeIntVal(i);
128fa0734ecSArgyrios Kyrtzidis }
129fa0734ecSArgyrios Kyrtzidis 
1305ad574c0SZhanyong Wan SVal SimpleSValBuilder::evalCastFromLoc(Loc val, QualType castTy) {
131fa0734ecSArgyrios Kyrtzidis 
132fa0734ecSArgyrios Kyrtzidis   // Casts from pointers -> pointers, just return the lval.
133fa0734ecSArgyrios Kyrtzidis   //
134fa0734ecSArgyrios Kyrtzidis   // Casts from pointers -> references, just return the lval.  These
135fa0734ecSArgyrios Kyrtzidis   //   can be introduced by the frontend for corner cases, e.g
136fa0734ecSArgyrios Kyrtzidis   //   casting from va_list* to __builtin_va_list&.
137fa0734ecSArgyrios Kyrtzidis   //
13885a203ebSZhanyong Wan   if (Loc::isLocType(castTy) || castTy->isReferenceType())
139fa0734ecSArgyrios Kyrtzidis     return val;
140fa0734ecSArgyrios Kyrtzidis 
141fa0734ecSArgyrios Kyrtzidis   // FIXME: Handle transparent unions where a value can be "transparently"
142fa0734ecSArgyrios Kyrtzidis   //  lifted into a union type.
143fa0734ecSArgyrios Kyrtzidis   if (castTy->isUnionType())
144fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
145fa0734ecSArgyrios Kyrtzidis 
146acd080b9SJordan Rose   // Casting a Loc to a bool will almost always be true,
147acd080b9SJordan Rose   // unless this is a weak function or a symbolic region.
148acd080b9SJordan Rose   if (castTy->isBooleanType()) {
149acd080b9SJordan Rose     switch (val.getSubKind()) {
15073f018e3SArtem Dergachev       case loc::MemRegionValKind: {
151acd080b9SJordan Rose         const MemRegion *R = val.castAs<loc::MemRegionVal>().getRegion();
15273f018e3SArtem Dergachev         if (const FunctionCodeRegion *FTR = dyn_cast<FunctionCodeRegion>(R))
153acd080b9SJordan Rose           if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FTR->getDecl()))
154acd080b9SJordan Rose             if (FD->isWeak())
155acd080b9SJordan Rose               // FIXME: Currently we are using an extent symbol here,
156acd080b9SJordan Rose               // because there are no generic region address metadata
157acd080b9SJordan Rose               // symbols to use, only content metadata.
158acd080b9SJordan Rose               return nonloc::SymbolVal(SymMgr.getExtentSymbol(FTR));
159acd080b9SJordan Rose 
160acd080b9SJordan Rose         if (const SymbolicRegion *SymR = R->getSymbolicBase())
16135dbd0b1SArtem Dergachev           return makeNonLoc(SymR->getSymbol(), BO_NE,
16235dbd0b1SArtem Dergachev                             BasicVals.getZeroWithPtrWidth(), castTy);
163acd080b9SJordan Rose 
164acd080b9SJordan Rose         // FALL-THROUGH
165a65d5785SGalina Kistanova         LLVM_FALLTHROUGH;
166acd080b9SJordan Rose       }
167acd080b9SJordan Rose 
168acd080b9SJordan Rose       case loc::GotoLabelKind:
169d4733638SAlp Toker         // Labels and non-symbolic memory regions are always true.
170acd080b9SJordan Rose         return makeTruthVal(true, castTy);
171acd080b9SJordan Rose     }
172acd080b9SJordan Rose   }
173acd080b9SJordan Rose 
17461e221f6SJordan Rose   if (castTy->isIntegralOrEnumerationType()) {
17559d10a4cSAlexander Shaposhnikov     unsigned BitWidth = Context.getIntWidth(castTy);
176fa0734ecSArgyrios Kyrtzidis 
1772fdacbc5SDavid Blaikie     if (!val.getAs<loc::ConcreteInt>())
178fa0734ecSArgyrios Kyrtzidis       return makeLocAsInteger(val, BitWidth);
179fa0734ecSArgyrios Kyrtzidis 
1802fdacbc5SDavid Blaikie     llvm::APSInt i = val.castAs<loc::ConcreteInt>().getValue();
1817e3c3ea3SJordy Rose     BasicVals.getAPSIntType(castTy).apply(i);
182fa0734ecSArgyrios Kyrtzidis     return makeIntVal(i);
183fa0734ecSArgyrios Kyrtzidis   }
184fa0734ecSArgyrios Kyrtzidis 
185fa0734ecSArgyrios Kyrtzidis   // All other cases: return 'UnknownVal'.  This includes casting pointers
186fa0734ecSArgyrios Kyrtzidis   // to floats, which is probably badness it itself, but this is a good
187fa0734ecSArgyrios Kyrtzidis   // intermediate solution until we do something better.
188fa0734ecSArgyrios Kyrtzidis   return UnknownVal();
189fa0734ecSArgyrios Kyrtzidis }
190fa0734ecSArgyrios Kyrtzidis 
191fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
192fa0734ecSArgyrios Kyrtzidis // Transfer function for unary operators.
193fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
194fa0734ecSArgyrios Kyrtzidis 
195fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::evalMinus(NonLoc val) {
196fa0734ecSArgyrios Kyrtzidis   switch (val.getSubKind()) {
197fa0734ecSArgyrios Kyrtzidis   case nonloc::ConcreteIntKind:
1982fdacbc5SDavid Blaikie     return val.castAs<nonloc::ConcreteInt>().evalMinus(*this);
199fa0734ecSArgyrios Kyrtzidis   default:
200fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
201fa0734ecSArgyrios Kyrtzidis   }
202fa0734ecSArgyrios Kyrtzidis }
203fa0734ecSArgyrios Kyrtzidis 
204fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::evalComplement(NonLoc X) {
205fa0734ecSArgyrios Kyrtzidis   switch (X.getSubKind()) {
206fa0734ecSArgyrios Kyrtzidis   case nonloc::ConcreteIntKind:
2072fdacbc5SDavid Blaikie     return X.castAs<nonloc::ConcreteInt>().evalComplement(*this);
208fa0734ecSArgyrios Kyrtzidis   default:
209fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
210fa0734ecSArgyrios Kyrtzidis   }
211fa0734ecSArgyrios Kyrtzidis }
212fa0734ecSArgyrios Kyrtzidis 
213fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
214fa0734ecSArgyrios Kyrtzidis // Transfer function for binary operators.
215fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===//
216fa0734ecSArgyrios Kyrtzidis 
217fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
218fa0734ecSArgyrios Kyrtzidis                                     BinaryOperator::Opcode op,
219fa0734ecSArgyrios Kyrtzidis                                     const llvm::APSInt &RHS,
220fa0734ecSArgyrios Kyrtzidis                                     QualType resultTy) {
221fa0734ecSArgyrios Kyrtzidis   bool isIdempotent = false;
222fa0734ecSArgyrios Kyrtzidis 
223fa0734ecSArgyrios Kyrtzidis   // Check for a few special cases with known reductions first.
224fa0734ecSArgyrios Kyrtzidis   switch (op) {
225fa0734ecSArgyrios Kyrtzidis   default:
226fa0734ecSArgyrios Kyrtzidis     // We can't reduce this case; just treat it normally.
227fa0734ecSArgyrios Kyrtzidis     break;
228fa0734ecSArgyrios Kyrtzidis   case BO_Mul:
229fa0734ecSArgyrios Kyrtzidis     // a*0 and a*1
230fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
231fa0734ecSArgyrios Kyrtzidis       return makeIntVal(0, resultTy);
232fa0734ecSArgyrios Kyrtzidis     else if (RHS == 1)
233fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
234fa0734ecSArgyrios Kyrtzidis     break;
235fa0734ecSArgyrios Kyrtzidis   case BO_Div:
236fa0734ecSArgyrios Kyrtzidis     // a/0 and a/1
237fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
238fa0734ecSArgyrios Kyrtzidis       // This is also handled elsewhere.
239fa0734ecSArgyrios Kyrtzidis       return UndefinedVal();
240fa0734ecSArgyrios Kyrtzidis     else if (RHS == 1)
241fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
242fa0734ecSArgyrios Kyrtzidis     break;
243fa0734ecSArgyrios Kyrtzidis   case BO_Rem:
244fa0734ecSArgyrios Kyrtzidis     // a%0 and a%1
245fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
246fa0734ecSArgyrios Kyrtzidis       // This is also handled elsewhere.
247fa0734ecSArgyrios Kyrtzidis       return UndefinedVal();
248fa0734ecSArgyrios Kyrtzidis     else if (RHS == 1)
249fa0734ecSArgyrios Kyrtzidis       return makeIntVal(0, resultTy);
250fa0734ecSArgyrios Kyrtzidis     break;
251fa0734ecSArgyrios Kyrtzidis   case BO_Add:
252fa0734ecSArgyrios Kyrtzidis   case BO_Sub:
253fa0734ecSArgyrios Kyrtzidis   case BO_Shl:
254fa0734ecSArgyrios Kyrtzidis   case BO_Shr:
255fa0734ecSArgyrios Kyrtzidis   case BO_Xor:
256fa0734ecSArgyrios Kyrtzidis     // a+0, a-0, a<<0, a>>0, a^0
257fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
258fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
259fa0734ecSArgyrios Kyrtzidis     break;
260fa0734ecSArgyrios Kyrtzidis   case BO_And:
261fa0734ecSArgyrios Kyrtzidis     // a&0 and a&(~0)
262fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
263fa0734ecSArgyrios Kyrtzidis       return makeIntVal(0, resultTy);
264fa0734ecSArgyrios Kyrtzidis     else if (RHS.isAllOnesValue())
265fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
266fa0734ecSArgyrios Kyrtzidis     break;
267fa0734ecSArgyrios Kyrtzidis   case BO_Or:
268fa0734ecSArgyrios Kyrtzidis     // a|0 and a|(~0)
269fa0734ecSArgyrios Kyrtzidis     if (RHS == 0)
270fa0734ecSArgyrios Kyrtzidis       isIdempotent = true;
271fa0734ecSArgyrios Kyrtzidis     else if (RHS.isAllOnesValue()) {
272fa0734ecSArgyrios Kyrtzidis       const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
273fa0734ecSArgyrios Kyrtzidis       return nonloc::ConcreteInt(Result);
274fa0734ecSArgyrios Kyrtzidis     }
275fa0734ecSArgyrios Kyrtzidis     break;
276fa0734ecSArgyrios Kyrtzidis   }
277fa0734ecSArgyrios Kyrtzidis 
278fa0734ecSArgyrios Kyrtzidis   // Idempotent ops (like a*1) can still change the type of an expression.
2795ad574c0SZhanyong Wan   // Wrap the LHS up in a NonLoc again and let evalCastFromNonLoc do the
2805ad574c0SZhanyong Wan   // dirty work.
281d066f79cSAnna Zaks   if (isIdempotent)
282a636fbe7SAnna Zaks       return evalCastFromNonLoc(nonloc::SymbolVal(LHS), resultTy);
283fa0734ecSArgyrios Kyrtzidis 
284fa0734ecSArgyrios Kyrtzidis   // If we reach this point, the expression cannot be simplified.
28554569448SJordy Rose   // Make a SymbolVal for the entire expression, after converting the RHS.
28654569448SJordy Rose   const llvm::APSInt *ConvertedRHS = &RHS;
28754569448SJordy Rose   if (BinaryOperator::isComparisonOp(op)) {
28854569448SJordy Rose     // We're looking for a type big enough to compare the symbolic value
28954569448SJordy Rose     // with the given constant.
29054569448SJordy Rose     // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
29154569448SJordy Rose     ASTContext &Ctx = getContext();
292a808e165STed Kremenek     QualType SymbolType = LHS->getType();
29354569448SJordy Rose     uint64_t ValWidth = RHS.getBitWidth();
29454569448SJordy Rose     uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
29554569448SJordy Rose 
29654569448SJordy Rose     if (ValWidth < TypeWidth) {
29754569448SJordy Rose       // If the value is too small, extend it.
29854569448SJordy Rose       ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
29954569448SJordy Rose     } else if (ValWidth == TypeWidth) {
30054569448SJordy Rose       // If the value is signed but the symbol is unsigned, do the comparison
30154569448SJordy Rose       // in unsigned space. [C99 6.3.1.8]
30254569448SJordy Rose       // (For the opposite case, the value is already unsigned.)
30354569448SJordy Rose       if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
30454569448SJordy Rose         ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
30554569448SJordy Rose     }
30654569448SJordy Rose   } else
30754569448SJordy Rose     ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
30854569448SJordy Rose 
30954569448SJordy Rose   return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
310fa0734ecSArgyrios Kyrtzidis }
311fa0734ecSArgyrios Kyrtzidis 
3122bbccca9SAdam Balogh // See if Sym is known to be a relation Rel with Bound.
3132bbccca9SAdam Balogh static bool isInRelation(BinaryOperator::Opcode Rel, SymbolRef Sym,
3142bbccca9SAdam Balogh                          llvm::APSInt Bound, ProgramStateRef State) {
3152bbccca9SAdam Balogh   SValBuilder &SVB = State->getStateManager().getSValBuilder();
3162bbccca9SAdam Balogh   SVal Result =
3172bbccca9SAdam Balogh       SVB.evalBinOpNN(State, Rel, nonloc::SymbolVal(Sym),
3182bbccca9SAdam Balogh                       nonloc::ConcreteInt(Bound), SVB.getConditionType());
3192bbccca9SAdam Balogh   if (auto DV = Result.getAs<DefinedSVal>()) {
3202bbccca9SAdam Balogh     return !State->assume(*DV, false);
3212bbccca9SAdam Balogh   }
3222bbccca9SAdam Balogh   return false;
3232bbccca9SAdam Balogh }
3242bbccca9SAdam Balogh 
3252bbccca9SAdam Balogh // See if Sym is known to be within [min/4, max/4], where min and max
3262bbccca9SAdam Balogh // are the bounds of the symbol's integral type. With such symbols,
3272bbccca9SAdam Balogh // some manipulations can be performed without the risk of overflow.
3282bbccca9SAdam Balogh // assume() doesn't cause infinite recursion because we should be dealing
3292bbccca9SAdam Balogh // with simpler symbols on every recursive call.
3302bbccca9SAdam Balogh static bool isWithinConstantOverflowBounds(SymbolRef Sym,
3312bbccca9SAdam Balogh                                            ProgramStateRef State) {
3322bbccca9SAdam Balogh   SValBuilder &SVB = State->getStateManager().getSValBuilder();
3332bbccca9SAdam Balogh   BasicValueFactory &BV = SVB.getBasicValueFactory();
3342bbccca9SAdam Balogh 
3352bbccca9SAdam Balogh   QualType T = Sym->getType();
3362bbccca9SAdam Balogh   assert(T->isSignedIntegerOrEnumerationType() &&
3372bbccca9SAdam Balogh          "This only works with signed integers!");
3382bbccca9SAdam Balogh   APSIntType AT = BV.getAPSIntType(T);
3392bbccca9SAdam Balogh 
3402bbccca9SAdam Balogh   llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
3412bbccca9SAdam Balogh   return isInRelation(BO_LE, Sym, Max, State) &&
3422bbccca9SAdam Balogh          isInRelation(BO_GE, Sym, Min, State);
3432bbccca9SAdam Balogh }
3442bbccca9SAdam Balogh 
3452bbccca9SAdam Balogh // Same for the concrete integers: see if I is within [min/4, max/4].
3462bbccca9SAdam Balogh static bool isWithinConstantOverflowBounds(llvm::APSInt I) {
3472bbccca9SAdam Balogh   APSIntType AT(I);
3482bbccca9SAdam Balogh   assert(!AT.isUnsigned() &&
3492bbccca9SAdam Balogh          "This only works with signed integers!");
3502bbccca9SAdam Balogh 
3512bbccca9SAdam Balogh   llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
3522bbccca9SAdam Balogh   return (I <= Max) && (I >= -Max);
3532bbccca9SAdam Balogh }
3542bbccca9SAdam Balogh 
3552bbccca9SAdam Balogh static std::pair<SymbolRef, llvm::APSInt>
3562bbccca9SAdam Balogh decomposeSymbol(SymbolRef Sym, BasicValueFactory &BV) {
3572bbccca9SAdam Balogh   if (const auto *SymInt = dyn_cast<SymIntExpr>(Sym))
3582bbccca9SAdam Balogh     if (BinaryOperator::isAdditiveOp(SymInt->getOpcode()))
3592bbccca9SAdam Balogh       return std::make_pair(SymInt->getLHS(),
3602bbccca9SAdam Balogh                             (SymInt->getOpcode() == BO_Add) ?
3612bbccca9SAdam Balogh                             (SymInt->getRHS()) :
3622bbccca9SAdam Balogh                             (-SymInt->getRHS()));
3632bbccca9SAdam Balogh 
3642bbccca9SAdam Balogh   // Fail to decompose: "reduce" the problem to the "$x + 0" case.
3652bbccca9SAdam Balogh   return std::make_pair(Sym, BV.getValue(0, Sym->getType()));
3662bbccca9SAdam Balogh }
3672bbccca9SAdam Balogh 
3682bbccca9SAdam Balogh // Simplify "(LSym + LInt) Op (RSym + RInt)" assuming all values are of the
3692bbccca9SAdam Balogh // same signed integral type and no overflows occur (which should be checked
3702bbccca9SAdam Balogh // by the caller).
3712bbccca9SAdam Balogh static NonLoc doRearrangeUnchecked(ProgramStateRef State,
3722bbccca9SAdam Balogh                                    BinaryOperator::Opcode Op,
3732bbccca9SAdam Balogh                                    SymbolRef LSym, llvm::APSInt LInt,
3742bbccca9SAdam Balogh                                    SymbolRef RSym, llvm::APSInt RInt) {
3752bbccca9SAdam Balogh   SValBuilder &SVB = State->getStateManager().getSValBuilder();
3762bbccca9SAdam Balogh   BasicValueFactory &BV = SVB.getBasicValueFactory();
3772bbccca9SAdam Balogh   SymbolManager &SymMgr = SVB.getSymbolManager();
3782bbccca9SAdam Balogh 
3792bbccca9SAdam Balogh   QualType SymTy = LSym->getType();
3802bbccca9SAdam Balogh   assert(SymTy == RSym->getType() &&
3812bbccca9SAdam Balogh          "Symbols are not of the same type!");
3822bbccca9SAdam Balogh   assert(APSIntType(LInt) == BV.getAPSIntType(SymTy) &&
3832bbccca9SAdam Balogh          "Integers are not of the same type as symbols!");
3842bbccca9SAdam Balogh   assert(APSIntType(RInt) == BV.getAPSIntType(SymTy) &&
3852bbccca9SAdam Balogh          "Integers are not of the same type as symbols!");
3862bbccca9SAdam Balogh 
3872bbccca9SAdam Balogh   QualType ResultTy;
3882bbccca9SAdam Balogh   if (BinaryOperator::isComparisonOp(Op))
3892bbccca9SAdam Balogh     ResultTy = SVB.getConditionType();
3902bbccca9SAdam Balogh   else if (BinaryOperator::isAdditiveOp(Op))
3912bbccca9SAdam Balogh     ResultTy = SymTy;
3922bbccca9SAdam Balogh   else
3932bbccca9SAdam Balogh     llvm_unreachable("Operation not suitable for unchecked rearrangement!");
3942bbccca9SAdam Balogh 
3952bbccca9SAdam Balogh   // FIXME: Can we use assume() without getting into an infinite recursion?
3962bbccca9SAdam Balogh   if (LSym == RSym)
3972bbccca9SAdam Balogh     return SVB.evalBinOpNN(State, Op, nonloc::ConcreteInt(LInt),
3982bbccca9SAdam Balogh                            nonloc::ConcreteInt(RInt), ResultTy)
3992bbccca9SAdam Balogh         .castAs<NonLoc>();
4002bbccca9SAdam Balogh 
4012bbccca9SAdam Balogh   SymbolRef ResultSym = nullptr;
4022bbccca9SAdam Balogh   BinaryOperator::Opcode ResultOp;
4032bbccca9SAdam Balogh   llvm::APSInt ResultInt;
4042bbccca9SAdam Balogh   if (BinaryOperator::isComparisonOp(Op)) {
4052bbccca9SAdam Balogh     // Prefer comparing to a non-negative number.
4062bbccca9SAdam Balogh     // FIXME: Maybe it'd be better to have consistency in
4072bbccca9SAdam Balogh     // "$x - $y" vs. "$y - $x" because those are solver's keys.
4082bbccca9SAdam Balogh     if (LInt > RInt) {
4092bbccca9SAdam Balogh       ResultSym = SymMgr.getSymSymExpr(RSym, BO_Sub, LSym, SymTy);
4102bbccca9SAdam Balogh       ResultOp = BinaryOperator::reverseComparisonOp(Op);
4112bbccca9SAdam Balogh       ResultInt = LInt - RInt; // Opposite order!
4122bbccca9SAdam Balogh     } else {
4132bbccca9SAdam Balogh       ResultSym = SymMgr.getSymSymExpr(LSym, BO_Sub, RSym, SymTy);
4142bbccca9SAdam Balogh       ResultOp = Op;
4152bbccca9SAdam Balogh       ResultInt = RInt - LInt; // Opposite order!
4162bbccca9SAdam Balogh     }
4172bbccca9SAdam Balogh   } else {
4182bbccca9SAdam Balogh     ResultSym = SymMgr.getSymSymExpr(LSym, Op, RSym, SymTy);
4192bbccca9SAdam Balogh     ResultInt = (Op == BO_Add) ? (LInt + RInt) : (LInt - RInt);
4202bbccca9SAdam Balogh     ResultOp = BO_Add;
4212bbccca9SAdam Balogh     // Bring back the cosmetic difference.
4222bbccca9SAdam Balogh     if (ResultInt < 0) {
4232bbccca9SAdam Balogh       ResultInt = -ResultInt;
4242bbccca9SAdam Balogh       ResultOp = BO_Sub;
4252bbccca9SAdam Balogh     } else if (ResultInt == 0) {
4262bbccca9SAdam Balogh       // Shortcut: Simplify "$x + 0" to "$x".
4272bbccca9SAdam Balogh       return nonloc::SymbolVal(ResultSym);
4282bbccca9SAdam Balogh     }
4292bbccca9SAdam Balogh   }
4302bbccca9SAdam Balogh   const llvm::APSInt &PersistentResultInt = BV.getValue(ResultInt);
4312bbccca9SAdam Balogh   return nonloc::SymbolVal(
4322bbccca9SAdam Balogh       SymMgr.getSymIntExpr(ResultSym, ResultOp, PersistentResultInt, ResultTy));
4332bbccca9SAdam Balogh }
4342bbccca9SAdam Balogh 
4352bbccca9SAdam Balogh // Rearrange if symbol type matches the result type and if the operator is a
4362bbccca9SAdam Balogh // comparison operator, both symbol and constant must be within constant
4372bbccca9SAdam Balogh // overflow bounds.
4382bbccca9SAdam Balogh static bool shouldRearrange(ProgramStateRef State, BinaryOperator::Opcode Op,
4392bbccca9SAdam Balogh                             SymbolRef Sym, llvm::APSInt Int, QualType Ty) {
4402bbccca9SAdam Balogh   return Sym->getType() == Ty &&
4412bbccca9SAdam Balogh     (!BinaryOperator::isComparisonOp(Op) ||
4422bbccca9SAdam Balogh      (isWithinConstantOverflowBounds(Sym, State) &&
4432bbccca9SAdam Balogh       isWithinConstantOverflowBounds(Int)));
4442bbccca9SAdam Balogh }
4452bbccca9SAdam Balogh 
4462bbccca9SAdam Balogh static Optional<NonLoc> tryRearrange(ProgramStateRef State,
4472bbccca9SAdam Balogh                                      BinaryOperator::Opcode Op, NonLoc Lhs,
4482bbccca9SAdam Balogh                                      NonLoc Rhs, QualType ResultTy) {
4492bbccca9SAdam Balogh   ProgramStateManager &StateMgr = State->getStateManager();
4502bbccca9SAdam Balogh   SValBuilder &SVB = StateMgr.getSValBuilder();
4512bbccca9SAdam Balogh 
4522bbccca9SAdam Balogh   // We expect everything to be of the same type - this type.
4532bbccca9SAdam Balogh   QualType SingleTy;
4542bbccca9SAdam Balogh 
4552bbccca9SAdam Balogh   auto &Opts =
45621aa8db6SGabor Horvath     StateMgr.getOwningEngine().getAnalysisManager().getAnalyzerOptions();
4572bbccca9SAdam Balogh 
458dcde8accSAdam Balogh   // FIXME: After putting complexity threshold to the symbols we can always
459dcde8accSAdam Balogh   //        rearrange additive operations but rearrange comparisons only if
460dcde8accSAdam Balogh   //        option is set.
461549f9cd4SKristof Umann   if(!Opts.ShouldAggressivelySimplifyBinaryOperation)
462dcde8accSAdam Balogh     return None;
463dcde8accSAdam Balogh 
4642bbccca9SAdam Balogh   SymbolRef LSym = Lhs.getAsSymbol();
4652bbccca9SAdam Balogh   if (!LSym)
4662bbccca9SAdam Balogh     return None;
4672bbccca9SAdam Balogh 
468dcde8accSAdam Balogh   if (BinaryOperator::isComparisonOp(Op)) {
4692bbccca9SAdam Balogh     SingleTy = LSym->getType();
4702bbccca9SAdam Balogh     if (ResultTy != SVB.getConditionType())
4712bbccca9SAdam Balogh       return None;
4722bbccca9SAdam Balogh     // Initialize SingleTy later with a symbol's type.
4732bbccca9SAdam Balogh   } else if (BinaryOperator::isAdditiveOp(Op)) {
4742bbccca9SAdam Balogh     SingleTy = ResultTy;
47513e186c0SAdam Balogh     if (LSym->getType() != SingleTy)
47613e186c0SAdam Balogh       return None;
4772bbccca9SAdam Balogh   } else {
4782bbccca9SAdam Balogh     // Don't rearrange other operations.
4792bbccca9SAdam Balogh     return None;
4802bbccca9SAdam Balogh   }
4812bbccca9SAdam Balogh 
4822bbccca9SAdam Balogh   assert(!SingleTy.isNull() && "We should have figured out the type by now!");
4832bbccca9SAdam Balogh 
484471d0864SAdam Balogh   // Rearrange signed symbolic expressions only
485471d0864SAdam Balogh   if (!SingleTy->isSignedIntegerOrEnumerationType())
486471d0864SAdam Balogh     return None;
487471d0864SAdam 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:
537bd3e5dbfSGeorge 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();
574*27ed855aSDavid Stenberg           // If the region has a symbolic base, pay attention to the type; it
575*27ed855aSDavid Stenberg           // might be coming from a non-default address space. For non-symbolic
576*27ed855aSDavid Stenberg           // regions it doesn't matter that much because such comparisons would
577*27ed855aSDavid Stenberg           // most likely evaluate to concrete false anyway. FIXME: We might
578*27ed855aSDavid Stenberg           // still need to handle the non-comparison case.
579*27ed855aSDavid Stenberg           if (SymbolRef lSym = lhs.getAsLocSymbol(true))
580*27ed855aSDavid Stenberg             BasicVals.getAPSIntType(lSym->getType()).apply(i);
581*27ed855aSDavid Stenberg           else
5827e3c3ea3SJordy Rose             BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
583fa0734ecSArgyrios Kyrtzidis           return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
584fa0734ecSArgyrios Kyrtzidis         }
585fa0734ecSArgyrios Kyrtzidis         default:
586fa0734ecSArgyrios Kyrtzidis           switch (op) {
587fa0734ecSArgyrios Kyrtzidis             case BO_EQ:
588fa0734ecSArgyrios Kyrtzidis               return makeTruthVal(false, resultTy);
589fa0734ecSArgyrios Kyrtzidis             case BO_NE:
590fa0734ecSArgyrios Kyrtzidis               return makeTruthVal(true, resultTy);
591fa0734ecSArgyrios Kyrtzidis             default:
592fa0734ecSArgyrios Kyrtzidis               // This case also handles pointer arithmetic.
593bd3e5dbfSGeorge Karpenkov               return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
594fa0734ecSArgyrios Kyrtzidis           }
595fa0734ecSArgyrios Kyrtzidis       }
596fa0734ecSArgyrios Kyrtzidis     }
597d066f79cSAnna Zaks     case nonloc::ConcreteIntKind: {
5982fdacbc5SDavid Blaikie       llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
599d066f79cSAnna Zaks 
60054569448SJordy Rose       // If we're dealing with two known constants, just perform the operation.
60154569448SJordy Rose       if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) {
60254569448SJordy Rose         llvm::APSInt RHSValue = *KnownRHSValue;
60354569448SJordy Rose         if (BinaryOperator::isComparisonOp(op)) {
60454569448SJordy Rose           // We're looking for a type big enough to compare the two values.
6057e3c3ea3SJordy Rose           // FIXME: This is not correct. char + short will result in a promotion
6067e3c3ea3SJordy Rose           // to int. Unfortunately we have lost types by this point.
6077e3c3ea3SJordy Rose           APSIntType CompareType = std::max(APSIntType(LHSValue),
6087e3c3ea3SJordy Rose                                             APSIntType(RHSValue));
6097e3c3ea3SJordy Rose           CompareType.apply(LHSValue);
6107e3c3ea3SJordy Rose           CompareType.apply(RHSValue);
61154569448SJordy Rose         } else if (!BinaryOperator::isShiftOp(op)) {
6127e3c3ea3SJordy Rose           APSIntType IntType = BasicVals.getAPSIntType(resultTy);
6137e3c3ea3SJordy Rose           IntType.apply(LHSValue);
6147e3c3ea3SJordy Rose           IntType.apply(RHSValue);
615d066f79cSAnna Zaks         }
616d066f79cSAnna Zaks 
61754569448SJordy Rose         const llvm::APSInt *Result =
61854569448SJordy Rose           BasicVals.evalAPSInt(op, LHSValue, RHSValue);
61954569448SJordy Rose         if (!Result)
62054569448SJordy Rose           return UndefinedVal();
62154569448SJordy Rose 
62254569448SJordy Rose         return nonloc::ConcreteInt(*Result);
62354569448SJordy Rose       }
624d066f79cSAnna Zaks 
625d066f79cSAnna Zaks       // Swap the left and right sides and flip the operator if doing so
626d066f79cSAnna Zaks       // allows us to better reason about the expression (this is a form
627d066f79cSAnna Zaks       // of expression canonicalization).
628d066f79cSAnna Zaks       // While we're at it, catch some special cases for non-commutative ops.
629d066f79cSAnna Zaks       switch (op) {
630d066f79cSAnna Zaks       case BO_LT:
631d066f79cSAnna Zaks       case BO_GT:
632d066f79cSAnna Zaks       case BO_LE:
633d066f79cSAnna Zaks       case BO_GE:
634604d0bbbSJordan Rose         op = BinaryOperator::reverseComparisonOp(op);
6354dc0b1acSReid Kleckner         LLVM_FALLTHROUGH;
636d066f79cSAnna Zaks       case BO_EQ:
637d066f79cSAnna Zaks       case BO_NE:
638d066f79cSAnna Zaks       case BO_Add:
639d066f79cSAnna Zaks       case BO_Mul:
640d066f79cSAnna Zaks       case BO_And:
641d066f79cSAnna Zaks       case BO_Xor:
642d066f79cSAnna Zaks       case BO_Or:
64354569448SJordy Rose         std::swap(lhs, rhs);
644d066f79cSAnna Zaks         continue;
645d066f79cSAnna Zaks       case BO_Shr:
64654569448SJordy Rose         // (~0)>>a
64754569448SJordy Rose         if (LHSValue.isAllOnesValue() && LHSValue.isSigned())
64854569448SJordy Rose           return evalCastFromNonLoc(lhs, resultTy);
6494dc0b1acSReid Kleckner         LLVM_FALLTHROUGH;
650d066f79cSAnna Zaks       case BO_Shl:
65154569448SJordy Rose         // 0<<a and 0>>a
65254569448SJordy Rose         if (LHSValue == 0)
65354569448SJordy Rose           return evalCastFromNonLoc(lhs, resultTy);
654bd3e5dbfSGeorge Karpenkov         return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
655d066f79cSAnna Zaks       default:
656bd3e5dbfSGeorge Karpenkov         return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
657d066f79cSAnna Zaks       }
658d066f79cSAnna Zaks     }
659d066f79cSAnna Zaks     case nonloc::SymbolValKind: {
66054569448SJordy Rose       // We only handle LHS as simple symbols or SymIntExprs.
6612fdacbc5SDavid Blaikie       SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
662d066f79cSAnna Zaks 
663d066f79cSAnna Zaks       // LHS is a symbolic expression.
66454569448SJordy Rose       if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
665fa0734ecSArgyrios Kyrtzidis 
666fa0734ecSArgyrios Kyrtzidis         // Is this a logical not? (!x is represented as x == 0.)
667fa0734ecSArgyrios Kyrtzidis         if (op == BO_EQ && rhs.isZeroConstant()) {
668fa0734ecSArgyrios Kyrtzidis           // We know how to negate certain expressions. Simplify them here.
669fa0734ecSArgyrios Kyrtzidis 
670fa0734ecSArgyrios Kyrtzidis           BinaryOperator::Opcode opc = symIntExpr->getOpcode();
671fa0734ecSArgyrios Kyrtzidis           switch (opc) {
672fa0734ecSArgyrios Kyrtzidis           default:
673fa0734ecSArgyrios Kyrtzidis             // We don't know how to negate this operation.
674fa0734ecSArgyrios Kyrtzidis             // Just handle it as if it were a normal comparison to 0.
675fa0734ecSArgyrios Kyrtzidis             break;
676fa0734ecSArgyrios Kyrtzidis           case BO_LAnd:
677fa0734ecSArgyrios Kyrtzidis           case BO_LOr:
67883d382b1SDavid Blaikie             llvm_unreachable("Logical operators handled by branching logic.");
679fa0734ecSArgyrios Kyrtzidis           case BO_Assign:
680fa0734ecSArgyrios Kyrtzidis           case BO_MulAssign:
681fa0734ecSArgyrios Kyrtzidis           case BO_DivAssign:
682fa0734ecSArgyrios Kyrtzidis           case BO_RemAssign:
683fa0734ecSArgyrios Kyrtzidis           case BO_AddAssign:
684fa0734ecSArgyrios Kyrtzidis           case BO_SubAssign:
685fa0734ecSArgyrios Kyrtzidis           case BO_ShlAssign:
686fa0734ecSArgyrios Kyrtzidis           case BO_ShrAssign:
687fa0734ecSArgyrios Kyrtzidis           case BO_AndAssign:
688fa0734ecSArgyrios Kyrtzidis           case BO_XorAssign:
689fa0734ecSArgyrios Kyrtzidis           case BO_OrAssign:
690fa0734ecSArgyrios Kyrtzidis           case BO_Comma:
69183d382b1SDavid Blaikie             llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
692fa0734ecSArgyrios Kyrtzidis           case BO_PtrMemD:
693fa0734ecSArgyrios Kyrtzidis           case BO_PtrMemI:
69483d382b1SDavid Blaikie             llvm_unreachable("Pointer arithmetic not handled here.");
695fa0734ecSArgyrios Kyrtzidis           case BO_LT:
696fa0734ecSArgyrios Kyrtzidis           case BO_GT:
697fa0734ecSArgyrios Kyrtzidis           case BO_LE:
698fa0734ecSArgyrios Kyrtzidis           case BO_GE:
699fa0734ecSArgyrios Kyrtzidis           case BO_EQ:
700fa0734ecSArgyrios Kyrtzidis           case BO_NE:
701dc16628cSJordan Rose             assert(resultTy->isBooleanType() ||
702dc16628cSJordan Rose                    resultTy == getConditionType());
703dc16628cSJordan Rose             assert(symIntExpr->getType()->isBooleanType() ||
704dc16628cSJordan Rose                    getContext().hasSameUnqualifiedType(symIntExpr->getType(),
705dc16628cSJordan Rose                                                        getConditionType()));
706fa0734ecSArgyrios Kyrtzidis             // Negate the comparison and make a value.
707604d0bbbSJordan Rose             opc = BinaryOperator::negateComparisonOp(opc);
708fa0734ecSArgyrios Kyrtzidis             return makeNonLoc(symIntExpr->getLHS(), opc,
709fa0734ecSArgyrios Kyrtzidis                 symIntExpr->getRHS(), resultTy);
710fa0734ecSArgyrios Kyrtzidis           }
711fa0734ecSArgyrios Kyrtzidis         }
712fa0734ecSArgyrios Kyrtzidis 
713fa0734ecSArgyrios Kyrtzidis         // For now, only handle expressions whose RHS is a constant.
71454569448SJordy Rose         if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) {
715fa0734ecSArgyrios Kyrtzidis           // If both the LHS and the current expression are additive,
71654569448SJordy Rose           // fold their constants and try again.
717fa0734ecSArgyrios Kyrtzidis           if (BinaryOperator::isAdditiveOp(op)) {
718fa0734ecSArgyrios Kyrtzidis             BinaryOperator::Opcode lop = symIntExpr->getOpcode();
719fa0734ecSArgyrios Kyrtzidis             if (BinaryOperator::isAdditiveOp(lop)) {
72054569448SJordy Rose               // Convert the two constants to a common type, then combine them.
72154569448SJordy Rose 
722fa0734ecSArgyrios Kyrtzidis               // resultTy may not be the best type to convert to, but it's
723fa0734ecSArgyrios Kyrtzidis               // probably the best choice in expressions with mixed type
724fa0734ecSArgyrios Kyrtzidis               // (such as x+1U+2LL). The rules for implicit conversions should
725fa0734ecSArgyrios Kyrtzidis               // choose a reasonable type to preserve the expression, and will
726fa0734ecSArgyrios Kyrtzidis               // at least match how the value is going to be used.
7277e3c3ea3SJordy Rose               APSIntType IntType = BasicVals.getAPSIntType(resultTy);
7287e3c3ea3SJordy Rose               const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
7297e3c3ea3SJordy Rose               const llvm::APSInt &second = IntType.convert(*RHSValue);
73054569448SJordy Rose 
731fa0734ecSArgyrios Kyrtzidis               const llvm::APSInt *newRHS;
732fa0734ecSArgyrios Kyrtzidis               if (lop == op)
733fa0734ecSArgyrios Kyrtzidis                 newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
734fa0734ecSArgyrios Kyrtzidis               else
735fa0734ecSArgyrios Kyrtzidis                 newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
73654569448SJordy Rose 
73754569448SJordy Rose               assert(newRHS && "Invalid operation despite common type!");
73854569448SJordy Rose               rhs = nonloc::ConcreteInt(*newRHS);
73954569448SJordy Rose               lhs = nonloc::SymbolVal(symIntExpr->getLHS());
74054569448SJordy Rose               op = lop;
74154569448SJordy Rose               continue;
742fa0734ecSArgyrios Kyrtzidis             }
743fa0734ecSArgyrios Kyrtzidis           }
744fa0734ecSArgyrios Kyrtzidis 
74554569448SJordy Rose           // Otherwise, make a SymIntExpr out of the expression.
74654569448SJordy Rose           return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
74754569448SJordy Rose         }
7483b4c3ea2SJordan Rose       }
749fa0734ecSArgyrios Kyrtzidis 
7503b4c3ea2SJordan Rose       // Does the symbolic expression simplify to a constant?
7513b4c3ea2SJordan Rose       // If so, "fold" the constant by setting 'lhs' to a ConcreteInt
7523b4c3ea2SJordan Rose       // and try again.
75312294f8dSArtem Dergachev       SVal simplifiedLhs = simplifySVal(state, lhs);
75412294f8dSArtem Dergachev       if (simplifiedLhs != lhs)
75512294f8dSArtem Dergachev         if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>()) {
75612294f8dSArtem Dergachev           lhs = *simplifiedLhsAsNonLoc;
757fa0734ecSArgyrios Kyrtzidis           continue;
758fa0734ecSArgyrios Kyrtzidis         }
759fa0734ecSArgyrios Kyrtzidis 
76054569448SJordy Rose       // Is the RHS a constant?
76154569448SJordy Rose       if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
76254569448SJordy Rose         return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
763fa0734ecSArgyrios Kyrtzidis 
7642bbccca9SAdam Balogh       if (Optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy))
7652bbccca9SAdam Balogh         return *V;
7662bbccca9SAdam Balogh 
76754569448SJordy Rose       // Give up -- this is not a symbolic expression we can handle.
768bd3e5dbfSGeorge Karpenkov       return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
769fa0734ecSArgyrios Kyrtzidis     }
770fa0734ecSArgyrios Kyrtzidis     }
771fa0734ecSArgyrios Kyrtzidis   }
772fa0734ecSArgyrios Kyrtzidis }
773fa0734ecSArgyrios Kyrtzidis 
774bac964e1SAnna Zaks static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR,
775bac964e1SAnna Zaks                                             const FieldRegion *RightFR,
776bac964e1SAnna Zaks                                             BinaryOperator::Opcode op,
777bac964e1SAnna Zaks                                             QualType resultTy,
778bac964e1SAnna Zaks                                             SimpleSValBuilder &SVB) {
779bac964e1SAnna Zaks   // Only comparisons are meaningful here!
780bac964e1SAnna Zaks   if (!BinaryOperator::isComparisonOp(op))
781bac964e1SAnna Zaks     return UnknownVal();
782bac964e1SAnna Zaks 
783bac964e1SAnna Zaks   // Next, see if the two FRs have the same super-region.
784bac964e1SAnna Zaks   // FIXME: This doesn't handle casts yet, and simply stripping the casts
785bac964e1SAnna Zaks   // doesn't help.
786bac964e1SAnna Zaks   if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
787bac964e1SAnna Zaks     return UnknownVal();
788bac964e1SAnna Zaks 
789bac964e1SAnna Zaks   const FieldDecl *LeftFD = LeftFR->getDecl();
790bac964e1SAnna Zaks   const FieldDecl *RightFD = RightFR->getDecl();
791bac964e1SAnna Zaks   const RecordDecl *RD = LeftFD->getParent();
792bac964e1SAnna Zaks 
793bac964e1SAnna Zaks   // Make sure the two FRs are from the same kind of record. Just in case!
794bac964e1SAnna Zaks   // FIXME: This is probably where inheritance would be a problem.
795bac964e1SAnna Zaks   if (RD != RightFD->getParent())
796bac964e1SAnna Zaks     return UnknownVal();
797bac964e1SAnna Zaks 
798bac964e1SAnna Zaks   // We know for sure that the two fields are not the same, since that
799bac964e1SAnna Zaks   // would have given us the same SVal.
800bac964e1SAnna Zaks   if (op == BO_EQ)
801bac964e1SAnna Zaks     return SVB.makeTruthVal(false, resultTy);
802bac964e1SAnna Zaks   if (op == BO_NE)
803bac964e1SAnna Zaks     return SVB.makeTruthVal(true, resultTy);
804bac964e1SAnna Zaks 
805bac964e1SAnna Zaks   // Iterate through the fields and see which one comes first.
806bac964e1SAnna Zaks   // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
807bac964e1SAnna Zaks   // members and the units in which bit-fields reside have addresses that
808bac964e1SAnna Zaks   // increase in the order in which they are declared."
809bac964e1SAnna Zaks   bool leftFirst = (op == BO_LT || op == BO_LE);
810e8a8baefSAaron Ballman   for (const auto *I : RD->fields()) {
811e8a8baefSAaron Ballman     if (I == LeftFD)
812bac964e1SAnna Zaks       return SVB.makeTruthVal(leftFirst, resultTy);
813e8a8baefSAaron Ballman     if (I == RightFD)
814bac964e1SAnna Zaks       return SVB.makeTruthVal(!leftFirst, resultTy);
815bac964e1SAnna Zaks   }
816bac964e1SAnna Zaks 
817bac964e1SAnna Zaks   llvm_unreachable("Fields not found in parent record's definition");
818bac964e1SAnna Zaks }
819bac964e1SAnna Zaks 
820fa0734ecSArgyrios Kyrtzidis // FIXME: all this logic will change if/when we have MemRegion::getLocation().
82149b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
822fa0734ecSArgyrios Kyrtzidis                                   BinaryOperator::Opcode op,
823fa0734ecSArgyrios Kyrtzidis                                   Loc lhs, Loc rhs,
824fa0734ecSArgyrios Kyrtzidis                                   QualType resultTy) {
825fa0734ecSArgyrios Kyrtzidis   // Only comparisons and subtractions are valid operations on two pointers.
826fa0734ecSArgyrios Kyrtzidis   // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
827fa0734ecSArgyrios Kyrtzidis   // However, if a pointer is casted to an integer, evalBinOpNN may end up
828fa0734ecSArgyrios Kyrtzidis   // calling this function with another operation (PR7527). We don't attempt to
829fa0734ecSArgyrios Kyrtzidis   // model this for now, but it could be useful, particularly when the
830fa0734ecSArgyrios Kyrtzidis   // "location" is actually an integer value that's been passed through a void*.
831fa0734ecSArgyrios Kyrtzidis   if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
832fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
833fa0734ecSArgyrios Kyrtzidis 
834fa0734ecSArgyrios Kyrtzidis   // Special cases for when both sides are identical.
835fa0734ecSArgyrios Kyrtzidis   if (lhs == rhs) {
836fa0734ecSArgyrios Kyrtzidis     switch (op) {
837fa0734ecSArgyrios Kyrtzidis     default:
83883d382b1SDavid Blaikie       llvm_unreachable("Unimplemented operation for two identical values");
839fa0734ecSArgyrios Kyrtzidis     case BO_Sub:
840fa0734ecSArgyrios Kyrtzidis       return makeZeroVal(resultTy);
841fa0734ecSArgyrios Kyrtzidis     case BO_EQ:
842fa0734ecSArgyrios Kyrtzidis     case BO_LE:
843fa0734ecSArgyrios Kyrtzidis     case BO_GE:
844fa0734ecSArgyrios Kyrtzidis       return makeTruthVal(true, resultTy);
845fa0734ecSArgyrios Kyrtzidis     case BO_NE:
846fa0734ecSArgyrios Kyrtzidis     case BO_LT:
847fa0734ecSArgyrios Kyrtzidis     case BO_GT:
848fa0734ecSArgyrios Kyrtzidis       return makeTruthVal(false, resultTy);
849fa0734ecSArgyrios Kyrtzidis     }
850fa0734ecSArgyrios Kyrtzidis   }
851fa0734ecSArgyrios Kyrtzidis 
852fa0734ecSArgyrios Kyrtzidis   switch (lhs.getSubKind()) {
853fa0734ecSArgyrios Kyrtzidis   default:
85483d382b1SDavid Blaikie     llvm_unreachable("Ordering not implemented for this Loc.");
855fa0734ecSArgyrios Kyrtzidis 
856fa0734ecSArgyrios Kyrtzidis   case loc::GotoLabelKind:
857fa0734ecSArgyrios Kyrtzidis     // The only thing we know about labels is that they're non-null.
858fa0734ecSArgyrios Kyrtzidis     if (rhs.isZeroConstant()) {
859fa0734ecSArgyrios Kyrtzidis       switch (op) {
860fa0734ecSArgyrios Kyrtzidis       default:
861fa0734ecSArgyrios Kyrtzidis         break;
862fa0734ecSArgyrios Kyrtzidis       case BO_Sub:
8635ad574c0SZhanyong Wan         return evalCastFromLoc(lhs, resultTy);
864fa0734ecSArgyrios Kyrtzidis       case BO_EQ:
865fa0734ecSArgyrios Kyrtzidis       case BO_LE:
866fa0734ecSArgyrios Kyrtzidis       case BO_LT:
867fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(false, resultTy);
868fa0734ecSArgyrios Kyrtzidis       case BO_NE:
869fa0734ecSArgyrios Kyrtzidis       case BO_GT:
870fa0734ecSArgyrios Kyrtzidis       case BO_GE:
871fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(true, resultTy);
872fa0734ecSArgyrios Kyrtzidis       }
873fa0734ecSArgyrios Kyrtzidis     }
874fa0734ecSArgyrios Kyrtzidis     // There may be two labels for the same location, and a function region may
875fa0734ecSArgyrios Kyrtzidis     // have the same address as a label at the start of the function (depending
876fa0734ecSArgyrios Kyrtzidis     // on the ABI).
877fa0734ecSArgyrios Kyrtzidis     // FIXME: we can probably do a comparison against other MemRegions, though.
878fa0734ecSArgyrios Kyrtzidis     // FIXME: is there a way to tell if two labels refer to the same location?
879fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
880fa0734ecSArgyrios Kyrtzidis 
881fa0734ecSArgyrios Kyrtzidis   case loc::ConcreteIntKind: {
882fa0734ecSArgyrios Kyrtzidis     // If one of the operands is a symbol and the other is a constant,
883fa0734ecSArgyrios Kyrtzidis     // build an expression for use by the constraint manager.
884fa0734ecSArgyrios Kyrtzidis     if (SymbolRef rSym = rhs.getAsLocSymbol()) {
885c0402c69SDominic Chen       // We can only build expressions with symbols on the left,
886c0402c69SDominic Chen       // so we need a reversible operator.
887c70f1d63SRichard Smith       if (!BinaryOperator::isComparisonOp(op) || op == BO_Cmp)
888c0402c69SDominic Chen         return UnknownVal();
88935610d21SDominic Chen 
890c0402c69SDominic Chen       const llvm::APSInt &lVal = lhs.castAs<loc::ConcreteInt>().getValue();
891604d0bbbSJordan Rose       op = BinaryOperator::reverseComparisonOp(op);
892604d0bbbSJordan Rose       return makeNonLoc(rSym, op, lVal, resultTy);
893fa0734ecSArgyrios Kyrtzidis     }
894fa0734ecSArgyrios Kyrtzidis 
895fa0734ecSArgyrios Kyrtzidis     // If both operands are constants, just perform the operation.
89605785d16SDavid Blaikie     if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
8972fdacbc5SDavid Blaikie       SVal ResultVal =
8982fdacbc5SDavid Blaikie           lhs.castAs<loc::ConcreteInt>().evalBinOp(BasicVals, op, *rInt);
8998eca04b2SJordan Rose       if (Optional<NonLoc> Result = ResultVal.getAs<NonLoc>())
9008eca04b2SJordan Rose         return evalCastFromNonLoc(*Result, resultTy);
9018eca04b2SJordan Rose 
9028eca04b2SJordan Rose       assert(!ResultVal.getAs<Loc>() && "Loc-Loc ops should not produce Locs");
903fa0734ecSArgyrios Kyrtzidis       return UnknownVal();
904fa0734ecSArgyrios Kyrtzidis     }
905fa0734ecSArgyrios Kyrtzidis 
906fa0734ecSArgyrios Kyrtzidis     // Special case comparisons against NULL.
907fa0734ecSArgyrios Kyrtzidis     // This must come after the test if the RHS is a symbol, which is used to
908fa0734ecSArgyrios Kyrtzidis     // build constraints. The address of any non-symbolic region is guaranteed
909fa0734ecSArgyrios Kyrtzidis     // to be non-NULL, as is any label.
9102fdacbc5SDavid Blaikie     assert(rhs.getAs<loc::MemRegionVal>() || rhs.getAs<loc::GotoLabel>());
911fa0734ecSArgyrios Kyrtzidis     if (lhs.isZeroConstant()) {
912fa0734ecSArgyrios Kyrtzidis       switch (op) {
913fa0734ecSArgyrios Kyrtzidis       default:
914fa0734ecSArgyrios Kyrtzidis         break;
915fa0734ecSArgyrios Kyrtzidis       case BO_EQ:
916fa0734ecSArgyrios Kyrtzidis       case BO_GT:
917fa0734ecSArgyrios Kyrtzidis       case BO_GE:
918fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(false, resultTy);
919fa0734ecSArgyrios Kyrtzidis       case BO_NE:
920fa0734ecSArgyrios Kyrtzidis       case BO_LT:
921fa0734ecSArgyrios Kyrtzidis       case BO_LE:
922fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(true, resultTy);
923fa0734ecSArgyrios Kyrtzidis       }
924fa0734ecSArgyrios Kyrtzidis     }
925fa0734ecSArgyrios Kyrtzidis 
926fa0734ecSArgyrios Kyrtzidis     // Comparing an arbitrary integer to a region or label address is
927fa0734ecSArgyrios Kyrtzidis     // completely unknowable.
928fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
929fa0734ecSArgyrios Kyrtzidis   }
93073f018e3SArtem Dergachev   case loc::MemRegionValKind: {
93105785d16SDavid Blaikie     if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
932fa0734ecSArgyrios Kyrtzidis       // If one of the operands is a symbol and the other is a constant,
933fa0734ecSArgyrios Kyrtzidis       // build an expression for use by the constraint manager.
934f4963ff1SAlexander Shaposhnikov       if (SymbolRef lSym = lhs.getAsLocSymbol(true)) {
935f4963ff1SAlexander Shaposhnikov         if (BinaryOperator::isComparisonOp(op))
936fa0734ecSArgyrios Kyrtzidis           return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
937f4963ff1SAlexander Shaposhnikov         return UnknownVal();
938f4963ff1SAlexander Shaposhnikov       }
939fa0734ecSArgyrios Kyrtzidis       // Special case comparisons to NULL.
940fa0734ecSArgyrios Kyrtzidis       // This must come after the test if the LHS is a symbol, which is used to
941fa0734ecSArgyrios Kyrtzidis       // build constraints. The address of any non-symbolic region is guaranteed
942fa0734ecSArgyrios Kyrtzidis       // to be non-NULL.
943fa0734ecSArgyrios Kyrtzidis       if (rInt->isZeroConstant()) {
944acd080b9SJordan Rose         if (op == BO_Sub)
9455ad574c0SZhanyong Wan           return evalCastFromLoc(lhs, resultTy);
946acd080b9SJordan Rose 
947acd080b9SJordan Rose         if (BinaryOperator::isComparisonOp(op)) {
948acd080b9SJordan Rose           QualType boolType = getContext().BoolTy;
949acd080b9SJordan Rose           NonLoc l = evalCastFromLoc(lhs, boolType).castAs<NonLoc>();
950acd080b9SJordan Rose           NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>();
951acd080b9SJordan Rose           return evalBinOpNN(state, op, l, r, resultTy);
952fa0734ecSArgyrios Kyrtzidis         }
953fa0734ecSArgyrios Kyrtzidis       }
954fa0734ecSArgyrios Kyrtzidis 
955fa0734ecSArgyrios Kyrtzidis       // Comparing a region to an arbitrary integer is completely unknowable.
956fa0734ecSArgyrios Kyrtzidis       return UnknownVal();
957fa0734ecSArgyrios Kyrtzidis     }
958fa0734ecSArgyrios Kyrtzidis 
959fa0734ecSArgyrios Kyrtzidis     // Get both values as regions, if possible.
960fa0734ecSArgyrios Kyrtzidis     const MemRegion *LeftMR = lhs.getAsRegion();
96173f018e3SArtem Dergachev     assert(LeftMR && "MemRegionValKind SVal doesn't have a region!");
962fa0734ecSArgyrios Kyrtzidis 
963fa0734ecSArgyrios Kyrtzidis     const MemRegion *RightMR = rhs.getAsRegion();
964fa0734ecSArgyrios Kyrtzidis     if (!RightMR)
965fa0734ecSArgyrios Kyrtzidis       // The RHS is probably a label, which in theory could address a region.
966fa0734ecSArgyrios Kyrtzidis       // FIXME: we can probably make a more useful statement about non-code
967fa0734ecSArgyrios Kyrtzidis       // regions, though.
968fa0734ecSArgyrios Kyrtzidis       return UnknownVal();
969fa0734ecSArgyrios Kyrtzidis 
970fa0734ecSArgyrios Kyrtzidis     const MemRegion *LeftBase = LeftMR->getBaseRegion();
971fa0734ecSArgyrios Kyrtzidis     const MemRegion *RightBase = RightMR->getBaseRegion();
9723b4c3ea2SJordan Rose     const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
9733b4c3ea2SJordan Rose     const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
9743b4c3ea2SJordan Rose     const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
9753563fde6SAnna Zaks 
9763563fde6SAnna Zaks     // If the two regions are from different known memory spaces they cannot be
9773563fde6SAnna Zaks     // equal. Also, assume that no symbolic region (whose memory space is
9783563fde6SAnna Zaks     // unknown) is on the stack.
9793563fde6SAnna Zaks     if (LeftMS != RightMS &&
9803563fde6SAnna Zaks         ((LeftMS != UnknownMS && RightMS != UnknownMS) ||
9813563fde6SAnna Zaks          (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
982fa0734ecSArgyrios Kyrtzidis       switch (op) {
983fa0734ecSArgyrios Kyrtzidis       default:
984fa0734ecSArgyrios Kyrtzidis         return UnknownVal();
985fa0734ecSArgyrios Kyrtzidis       case BO_EQ:
986fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(false, resultTy);
987fa0734ecSArgyrios Kyrtzidis       case BO_NE:
988fa0734ecSArgyrios Kyrtzidis         return makeTruthVal(true, resultTy);
989fa0734ecSArgyrios Kyrtzidis       }
990fa0734ecSArgyrios Kyrtzidis     }
991fa0734ecSArgyrios Kyrtzidis 
9923563fde6SAnna Zaks     // If both values wrap regions, see if they're from different base regions.
9933563fde6SAnna Zaks     // Note, heap base symbolic regions are assumed to not alias with
9943563fde6SAnna Zaks     // each other; for example, we assume that malloc returns different address
9953563fde6SAnna Zaks     // on each invocation.
996aacc03c9SArtem Dergachev     // FIXME: ObjC object pointers always reside on the heap, but currently
997aacc03c9SArtem Dergachev     // we treat their memory space as unknown, because symbolic pointers
998aacc03c9SArtem Dergachev     // to ObjC objects may alias. There should be a way to construct
999aacc03c9SArtem Dergachev     // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker
1000aacc03c9SArtem Dergachev     // guesses memory space for ObjC object pointers manually instead of
1001aacc03c9SArtem Dergachev     // relying on us.
10023563fde6SAnna Zaks     if (LeftBase != RightBase &&
10033563fde6SAnna Zaks         ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
1004a7dcc996SAnna Zaks          (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
10059d96f843STed Kremenek       switch (op) {
10069d96f843STed Kremenek       default:
10073563fde6SAnna Zaks         return UnknownVal();
10089d96f843STed Kremenek       case BO_EQ:
10099d96f843STed Kremenek         return makeTruthVal(false, resultTy);
10109d96f843STed Kremenek       case BO_NE:
10119d96f843STed Kremenek         return makeTruthVal(true, resultTy);
10129d96f843STed Kremenek       }
10139d96f843STed Kremenek     }
1014fa0734ecSArgyrios Kyrtzidis 
1015bac964e1SAnna Zaks     // Handle special cases for when both regions are element regions.
1016fa0734ecSArgyrios Kyrtzidis     const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
1017bac964e1SAnna Zaks     const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR);
1018bac964e1SAnna Zaks     if (RightER && LeftER) {
1019fa0734ecSArgyrios Kyrtzidis       // Next, see if the two ERs have the same super-region and matching types.
1020fa0734ecSArgyrios Kyrtzidis       // FIXME: This should do something useful even if the types don't match,
1021fa0734ecSArgyrios Kyrtzidis       // though if both indexes are constant the RegionRawOffset path will
1022fa0734ecSArgyrios Kyrtzidis       // give the correct answer.
1023fa0734ecSArgyrios Kyrtzidis       if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
1024fa0734ecSArgyrios Kyrtzidis           LeftER->getElementType() == RightER->getElementType()) {
1025fa0734ecSArgyrios Kyrtzidis         // Get the left index and cast it to the correct type.
1026fa0734ecSArgyrios Kyrtzidis         // If the index is unknown or undefined, bail out here.
1027fa0734ecSArgyrios Kyrtzidis         SVal LeftIndexVal = LeftER->getIndex();
102805785d16SDavid Blaikie         Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
1029fa0734ecSArgyrios Kyrtzidis         if (!LeftIndex)
1030fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
10312317f30fSTed Kremenek         LeftIndexVal = evalCastFromNonLoc(*LeftIndex, ArrayIndexTy);
10322fdacbc5SDavid Blaikie         LeftIndex = LeftIndexVal.getAs<NonLoc>();
1033fa0734ecSArgyrios Kyrtzidis         if (!LeftIndex)
1034fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
1035fa0734ecSArgyrios Kyrtzidis 
1036fa0734ecSArgyrios Kyrtzidis         // Do the same for the right index.
1037fa0734ecSArgyrios Kyrtzidis         SVal RightIndexVal = RightER->getIndex();
103805785d16SDavid Blaikie         Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
1039fa0734ecSArgyrios Kyrtzidis         if (!RightIndex)
1040fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
10412317f30fSTed Kremenek         RightIndexVal = evalCastFromNonLoc(*RightIndex, ArrayIndexTy);
10422fdacbc5SDavid Blaikie         RightIndex = RightIndexVal.getAs<NonLoc>();
1043fa0734ecSArgyrios Kyrtzidis         if (!RightIndex)
1044fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
1045fa0734ecSArgyrios Kyrtzidis 
1046fa0734ecSArgyrios Kyrtzidis         // Actually perform the operation.
1047fa0734ecSArgyrios Kyrtzidis         // evalBinOpNN expects the two indexes to already be the right type.
1048fa0734ecSArgyrios Kyrtzidis         return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
1049fa0734ecSArgyrios Kyrtzidis       }
1050bac964e1SAnna Zaks     }
1051fa0734ecSArgyrios Kyrtzidis 
1052bac964e1SAnna Zaks     // Special handling of the FieldRegions, even with symbolic offsets.
1053bac964e1SAnna Zaks     const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
1054bac964e1SAnna Zaks     const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR);
1055bac964e1SAnna Zaks     if (RightFR && LeftFR) {
1056bac964e1SAnna Zaks       SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy,
1057bac964e1SAnna Zaks                                                *this);
1058bac964e1SAnna Zaks       if (!R.isUnknown())
1059bac964e1SAnna Zaks         return R;
1060bac964e1SAnna Zaks     }
1061bac964e1SAnna Zaks 
1062bac964e1SAnna Zaks     // Compare the regions using the raw offsets.
1063bac964e1SAnna Zaks     RegionOffset LeftOffset = LeftMR->getAsOffset();
1064bac964e1SAnna Zaks     RegionOffset RightOffset = RightMR->getAsOffset();
1065fa0734ecSArgyrios Kyrtzidis 
10660dbb783cSCraig Topper     if (LeftOffset.getRegion() != nullptr &&
1067bac964e1SAnna Zaks         LeftOffset.getRegion() == RightOffset.getRegion() &&
1068bac964e1SAnna Zaks         !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) {
1069bac964e1SAnna Zaks       int64_t left = LeftOffset.getOffset();
1070bac964e1SAnna Zaks       int64_t right = RightOffset.getOffset();
1071fa0734ecSArgyrios Kyrtzidis 
1072fa0734ecSArgyrios Kyrtzidis       switch (op) {
1073fa0734ecSArgyrios Kyrtzidis         default:
1074fa0734ecSArgyrios Kyrtzidis           return UnknownVal();
1075fa0734ecSArgyrios Kyrtzidis         case BO_LT:
1076fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left < right, resultTy);
1077fa0734ecSArgyrios Kyrtzidis         case BO_GT:
1078fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left > right, resultTy);
1079fa0734ecSArgyrios Kyrtzidis         case BO_LE:
1080fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left <= right, resultTy);
1081fa0734ecSArgyrios Kyrtzidis         case BO_GE:
1082fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left >= right, resultTy);
1083fa0734ecSArgyrios Kyrtzidis         case BO_EQ:
1084fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left == right, resultTy);
1085fa0734ecSArgyrios Kyrtzidis         case BO_NE:
1086fa0734ecSArgyrios Kyrtzidis           return makeTruthVal(left != right, resultTy);
1087fa0734ecSArgyrios Kyrtzidis       }
1088fa0734ecSArgyrios Kyrtzidis     }
1089fa0734ecSArgyrios Kyrtzidis 
10903b4c3ea2SJordan Rose     // At this point we're not going to get a good answer, but we can try
10913b4c3ea2SJordan Rose     // conjuring an expression instead.
10923b4c3ea2SJordan Rose     SymbolRef LHSSym = lhs.getAsLocSymbol();
10933b4c3ea2SJordan Rose     SymbolRef RHSSym = rhs.getAsLocSymbol();
10943b4c3ea2SJordan Rose     if (LHSSym && RHSSym)
10953b4c3ea2SJordan Rose       return makeNonLoc(LHSSym, op, RHSSym, resultTy);
10963b4c3ea2SJordan Rose 
1097fa0734ecSArgyrios Kyrtzidis     // If we get here, we have no way of comparing the regions.
1098fa0734ecSArgyrios Kyrtzidis     return UnknownVal();
1099fa0734ecSArgyrios Kyrtzidis   }
1100fa0734ecSArgyrios Kyrtzidis   }
1101fa0734ecSArgyrios Kyrtzidis }
1102fa0734ecSArgyrios Kyrtzidis 
110349b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
1104fa0734ecSArgyrios Kyrtzidis                                   BinaryOperator::Opcode op,
1105fa0734ecSArgyrios Kyrtzidis                                   Loc lhs, NonLoc rhs, QualType resultTy) {
110664c01f7bSDevin Coughlin   if (op >= BO_PtrMemD && op <= BO_PtrMemI) {
110764c01f7bSDevin Coughlin     if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) {
110864c01f7bSDevin Coughlin       if (PTMSV->isNullMemberPointer())
110964c01f7bSDevin Coughlin         return UndefinedVal();
111064c01f7bSDevin Coughlin       if (const FieldDecl *FD = PTMSV->getDeclAs<FieldDecl>()) {
111164c01f7bSDevin Coughlin         SVal Result = lhs;
111264c01f7bSDevin Coughlin 
111364c01f7bSDevin Coughlin         for (const auto &I : *PTMSV)
111464c01f7bSDevin Coughlin           Result = StateMgr.getStoreManager().evalDerivedToBase(
111564c01f7bSDevin Coughlin               Result, I->getType(),I->isVirtual());
111664c01f7bSDevin Coughlin         return state->getLValue(FD, Result);
111764c01f7bSDevin Coughlin       }
111864c01f7bSDevin Coughlin     }
111964c01f7bSDevin Coughlin 
112064c01f7bSDevin Coughlin     return rhs;
112164c01f7bSDevin Coughlin   }
112264c01f7bSDevin Coughlin 
1123686df322SJordan Rose   assert(!BinaryOperator::isComparisonOp(op) &&
1124686df322SJordan Rose          "arguments to comparison ops must be of the same type");
1125fa0734ecSArgyrios Kyrtzidis 
1126fa0734ecSArgyrios Kyrtzidis   // Special case: rhs is a zero constant.
1127fa0734ecSArgyrios Kyrtzidis   if (rhs.isZeroConstant())
1128fa0734ecSArgyrios Kyrtzidis     return lhs;
1129fa0734ecSArgyrios Kyrtzidis 
113021524676SGabor Horvath   // Perserve the null pointer so that it can be found by the DerefChecker.
113121524676SGabor Horvath   if (lhs.isZeroConstant())
113221524676SGabor Horvath     return lhs;
113321524676SGabor Horvath 
1134fa0734ecSArgyrios Kyrtzidis   // We are dealing with pointer arithmetic.
1135fa0734ecSArgyrios Kyrtzidis 
1136fa0734ecSArgyrios Kyrtzidis   // Handle pointer arithmetic on constant values.
113705785d16SDavid Blaikie   if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) {
113805785d16SDavid Blaikie     if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) {
1139fa0734ecSArgyrios Kyrtzidis       const llvm::APSInt &leftI = lhsInt->getValue();
1140fa0734ecSArgyrios Kyrtzidis       assert(leftI.isUnsigned());
1141fa0734ecSArgyrios Kyrtzidis       llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
1142fa0734ecSArgyrios Kyrtzidis 
1143fa0734ecSArgyrios Kyrtzidis       // Convert the bitwidth of rightI.  This should deal with overflow
1144fa0734ecSArgyrios Kyrtzidis       // since we are dealing with concrete values.
1145fa0734ecSArgyrios Kyrtzidis       rightI = rightI.extOrTrunc(leftI.getBitWidth());
1146fa0734ecSArgyrios Kyrtzidis 
1147fa0734ecSArgyrios Kyrtzidis       // Offset the increment by the pointer size.
1148fa0734ecSArgyrios Kyrtzidis       llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
114921524676SGabor Horvath       QualType pointeeType = resultTy->getPointeeType();
115021524676SGabor Horvath       Multiplicand = getContext().getTypeSizeInChars(pointeeType).getQuantity();
1151fa0734ecSArgyrios Kyrtzidis       rightI *= Multiplicand;
1152fa0734ecSArgyrios Kyrtzidis 
1153fa0734ecSArgyrios Kyrtzidis       // Compute the adjusted pointer.
1154fa0734ecSArgyrios Kyrtzidis       switch (op) {
1155fa0734ecSArgyrios Kyrtzidis         case BO_Add:
1156fa0734ecSArgyrios Kyrtzidis           rightI = leftI + rightI;
1157fa0734ecSArgyrios Kyrtzidis           break;
1158fa0734ecSArgyrios Kyrtzidis         case BO_Sub:
1159fa0734ecSArgyrios Kyrtzidis           rightI = leftI - rightI;
1160fa0734ecSArgyrios Kyrtzidis           break;
1161fa0734ecSArgyrios Kyrtzidis         default:
1162fa0734ecSArgyrios Kyrtzidis           llvm_unreachable("Invalid pointer arithmetic operation");
1163fa0734ecSArgyrios Kyrtzidis       }
1164fa0734ecSArgyrios Kyrtzidis       return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
1165fa0734ecSArgyrios Kyrtzidis     }
1166fa0734ecSArgyrios Kyrtzidis   }
1167fa0734ecSArgyrios Kyrtzidis 
1168fa0734ecSArgyrios Kyrtzidis   // Handle cases where 'lhs' is a region.
1169fa0734ecSArgyrios Kyrtzidis   if (const MemRegion *region = lhs.getAsRegion()) {
11702fdacbc5SDavid Blaikie     rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
1171fa0734ecSArgyrios Kyrtzidis     SVal index = UnknownVal();
11726dd11048SArtem Dergachev     const SubRegion *superR = nullptr;
11737333a9eaSArtem Dergachev     // We need to know the type of the pointer in order to add an integer to it.
11747333a9eaSArtem Dergachev     // Depending on the type, different amount of bytes is added.
1175fa0734ecSArgyrios Kyrtzidis     QualType elementType;
1176fa0734ecSArgyrios Kyrtzidis 
1177fa0734ecSArgyrios Kyrtzidis     if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
117857a4a152STed Kremenek       assert(op == BO_Add || op == BO_Sub);
117957a4a152STed Kremenek       index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
1180fa0734ecSArgyrios Kyrtzidis                           getArrayIndexType());
11816dd11048SArtem Dergachev       superR = cast<SubRegion>(elemReg->getSuperRegion());
1182fa0734ecSArgyrios Kyrtzidis       elementType = elemReg->getElementType();
1183fa0734ecSArgyrios Kyrtzidis     }
1184fa0734ecSArgyrios Kyrtzidis     else if (isa<SubRegion>(region)) {
1185c4b28a8fSGabor Horvath       assert(op == BO_Add || op == BO_Sub);
1186c4b28a8fSGabor Horvath       index = (op == BO_Add) ? rhs : evalMinus(rhs);
11876dd11048SArtem Dergachev       superR = cast<SubRegion>(region);
11887333a9eaSArtem Dergachev       // TODO: Is this actually reliable? Maybe improving our MemRegion
11897333a9eaSArtem Dergachev       // hierarchy to provide typed regions for all non-void pointers would be
11907333a9eaSArtem Dergachev       // better. For instance, we cannot extend this towards LocAsInteger
11917333a9eaSArtem Dergachev       // operations, where result type of the expression is integer.
1192d1a08b6eSJordan Rose       if (resultTy->isAnyPointerType())
1193d1a08b6eSJordan Rose         elementType = resultTy->getPointeeType();
1194fa0734ecSArgyrios Kyrtzidis     }
1195fa0734ecSArgyrios Kyrtzidis 
1196df1bb8a6SArtem Dergachev     // Represent arithmetic on void pointers as arithmetic on char pointers.
1197df1bb8a6SArtem Dergachev     // It is fine when a TypedValueRegion of char value type represents
1198df1bb8a6SArtem Dergachev     // a void pointer. Note that arithmetic on void pointers is a GCC extension.
1199df1bb8a6SArtem Dergachev     if (elementType->isVoidType())
1200df1bb8a6SArtem Dergachev       elementType = getContext().CharTy;
1201df1bb8a6SArtem Dergachev 
120205785d16SDavid Blaikie     if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) {
1203fa0734ecSArgyrios Kyrtzidis       return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
1204fa0734ecSArgyrios Kyrtzidis                                                        superR, getContext()));
1205fa0734ecSArgyrios Kyrtzidis     }
1206fa0734ecSArgyrios Kyrtzidis   }
1207fa0734ecSArgyrios Kyrtzidis   return UnknownVal();
1208fa0734ecSArgyrios Kyrtzidis }
1209fa0734ecSArgyrios Kyrtzidis 
121049b1e38eSTed Kremenek const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
1211fa0734ecSArgyrios Kyrtzidis                                                    SVal V) {
12129ff67a9dSGeorge Karpenkov   V = simplifySVal(state, V);
1213fa0734ecSArgyrios Kyrtzidis   if (V.isUnknownOrUndef())
12140dbb783cSCraig Topper     return nullptr;
1215fa0734ecSArgyrios Kyrtzidis 
121605785d16SDavid Blaikie   if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
1217fa0734ecSArgyrios Kyrtzidis     return &X->getValue();
1218fa0734ecSArgyrios Kyrtzidis 
121905785d16SDavid Blaikie   if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
1220fa0734ecSArgyrios Kyrtzidis     return &X->getValue();
1221fa0734ecSArgyrios Kyrtzidis 
1222fa0734ecSArgyrios Kyrtzidis   if (SymbolRef Sym = V.getAsSymbol())
1223244e1d7dSTed Kremenek     return state->getConstraintManager().getSymVal(state, Sym);
1224fa0734ecSArgyrios Kyrtzidis 
1225c0402c69SDominic Chen   // FIXME: Add support for SymExprs.
12260dbb783cSCraig Topper   return nullptr;
1227fa0734ecSArgyrios Kyrtzidis }
122812294f8dSArtem Dergachev 
122912294f8dSArtem Dergachev SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) {
123012294f8dSArtem Dergachev   // For now, this function tries to constant-fold symbols inside a
123112294f8dSArtem Dergachev   // nonloc::SymbolVal, and does nothing else. More simplifications should
123212294f8dSArtem Dergachev   // be possible, such as constant-folding an index in an ElementRegion.
123312294f8dSArtem Dergachev 
123412294f8dSArtem Dergachev   class Simplifier : public FullSValVisitor<Simplifier, SVal> {
123512294f8dSArtem Dergachev     ProgramStateRef State;
123612294f8dSArtem Dergachev     SValBuilder &SVB;
123712294f8dSArtem Dergachev 
123822746d7dSArtem Dergachev     // Cache results for the lifetime of the Simplifier. Results change every
123922746d7dSArtem Dergachev     // time new constraints are added to the program state, which is the whole
124022746d7dSArtem Dergachev     // point of simplifying, and for that very reason it's pointless to maintain
124122746d7dSArtem Dergachev     // the same cache for the duration of the whole analysis.
124222746d7dSArtem Dergachev     llvm::DenseMap<SymbolRef, SVal> Cached;
124322746d7dSArtem Dergachev 
124416a1f64cSArtem Dergachev     static bool isUnchanged(SymbolRef Sym, SVal Val) {
124516a1f64cSArtem Dergachev       return Sym == Val.getAsSymbol();
124616a1f64cSArtem Dergachev     }
124716a1f64cSArtem Dergachev 
12489fe9a95fSArtem Dergachev     SVal cache(SymbolRef Sym, SVal V) {
12499fe9a95fSArtem Dergachev       Cached[Sym] = V;
12509fe9a95fSArtem Dergachev       return V;
12519fe9a95fSArtem Dergachev     }
12529fe9a95fSArtem Dergachev 
12539fe9a95fSArtem Dergachev     SVal skip(SymbolRef Sym) {
12549fe9a95fSArtem Dergachev       return cache(Sym, SVB.makeSymbolVal(Sym));
12559fe9a95fSArtem Dergachev     }
12569fe9a95fSArtem Dergachev 
125712294f8dSArtem Dergachev   public:
125812294f8dSArtem Dergachev     Simplifier(ProgramStateRef State)
125912294f8dSArtem Dergachev         : State(State), SVB(State->getStateManager().getSValBuilder()) {}
126012294f8dSArtem Dergachev 
126112294f8dSArtem Dergachev     SVal VisitSymbolData(const SymbolData *S) {
12629fe9a95fSArtem Dergachev       // No cache here.
126312294f8dSArtem Dergachev       if (const llvm::APSInt *I =
1264d1163790SArtem Dergachev               SVB.getKnownValue(State, SVB.makeSymbolVal(S)))
126512294f8dSArtem Dergachev         return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I)
126612294f8dSArtem Dergachev                                             : (SVal)SVB.makeIntVal(*I);
126716a1f64cSArtem Dergachev       return SVB.makeSymbolVal(S);
126812294f8dSArtem Dergachev     }
126912294f8dSArtem Dergachev 
1270c0402c69SDominic Chen     // TODO: Support SymbolCast. Support IntSymExpr when/if we actually
1271c0402c69SDominic Chen     // start producing them.
127212294f8dSArtem Dergachev 
127312294f8dSArtem Dergachev     SVal VisitSymIntExpr(const SymIntExpr *S) {
127422746d7dSArtem Dergachev       auto I = Cached.find(S);
127522746d7dSArtem Dergachev       if (I != Cached.end())
127622746d7dSArtem Dergachev         return I->second;
127722746d7dSArtem Dergachev 
127812294f8dSArtem Dergachev       SVal LHS = Visit(S->getLHS());
12799fe9a95fSArtem Dergachev       if (isUnchanged(S->getLHS(), LHS))
12809fe9a95fSArtem Dergachev         return skip(S);
12819fe9a95fSArtem Dergachev 
128212294f8dSArtem Dergachev       SVal RHS;
128312294f8dSArtem Dergachev       // By looking at the APSInt in the right-hand side of S, we cannot
128412294f8dSArtem Dergachev       // figure out if it should be treated as a Loc or as a NonLoc.
128512294f8dSArtem Dergachev       // So make our guess by recalling that we cannot multiply pointers
128612294f8dSArtem Dergachev       // or compare a pointer to an integer.
128712294f8dSArtem Dergachev       if (Loc::isLocType(S->getLHS()->getType()) &&
128812294f8dSArtem Dergachev           BinaryOperator::isComparisonOp(S->getOpcode())) {
128912294f8dSArtem Dergachev         // The usual conversion of $sym to &SymRegion{$sym}, as they have
129012294f8dSArtem Dergachev         // the same meaning for Loc-type symbols, but the latter form
129112294f8dSArtem Dergachev         // is preferred in SVal computations for being Loc itself.
129212294f8dSArtem Dergachev         if (SymbolRef Sym = LHS.getAsSymbol()) {
129312294f8dSArtem Dergachev           assert(Loc::isLocType(Sym->getType()));
129412294f8dSArtem Dergachev           LHS = SVB.makeLoc(Sym);
129512294f8dSArtem Dergachev         }
129612294f8dSArtem Dergachev         RHS = SVB.makeIntLocVal(S->getRHS());
129712294f8dSArtem Dergachev       } else {
129812294f8dSArtem Dergachev         RHS = SVB.makeIntVal(S->getRHS());
129912294f8dSArtem Dergachev       }
130022746d7dSArtem Dergachev 
13019fe9a95fSArtem Dergachev       return cache(
13029fe9a95fSArtem Dergachev           S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
130312294f8dSArtem Dergachev     }
130412294f8dSArtem Dergachev 
130512294f8dSArtem Dergachev     SVal VisitSymSymExpr(const SymSymExpr *S) {
130622746d7dSArtem Dergachev       auto I = Cached.find(S);
130722746d7dSArtem Dergachev       if (I != Cached.end())
130822746d7dSArtem Dergachev         return I->second;
130922746d7dSArtem Dergachev 
131005220a90SArtem Dergachev       // For now don't try to simplify mixed Loc/NonLoc expressions
131105220a90SArtem Dergachev       // because they often appear from LocAsInteger operations
131205220a90SArtem Dergachev       // and we don't know how to combine a LocAsInteger
131305220a90SArtem Dergachev       // with a concrete value.
131405220a90SArtem Dergachev       if (Loc::isLocType(S->getLHS()->getType()) !=
13159fe9a95fSArtem Dergachev           Loc::isLocType(S->getRHS()->getType()))
13169fe9a95fSArtem Dergachev         return skip(S);
131705220a90SArtem Dergachev 
131812294f8dSArtem Dergachev       SVal LHS = Visit(S->getLHS());
131912294f8dSArtem Dergachev       SVal RHS = Visit(S->getRHS());
13209fe9a95fSArtem Dergachev       if (isUnchanged(S->getLHS(), LHS) && isUnchanged(S->getRHS(), RHS))
13219fe9a95fSArtem Dergachev         return skip(S);
13229fe9a95fSArtem Dergachev 
13239fe9a95fSArtem Dergachev       return cache(
13249fe9a95fSArtem Dergachev           S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
132512294f8dSArtem Dergachev     }
132612294f8dSArtem Dergachev 
132712294f8dSArtem Dergachev     SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); }
132812294f8dSArtem Dergachev 
132912294f8dSArtem Dergachev     SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); }
133012294f8dSArtem Dergachev 
133112294f8dSArtem Dergachev     SVal VisitNonLocSymbolVal(nonloc::SymbolVal V) {
133212294f8dSArtem Dergachev       // Simplification is much more costly than computing complexity.
133312294f8dSArtem Dergachev       // For high complexity, it may be not worth it.
133412294f8dSArtem Dergachev       return Visit(V.getSymbol());
133512294f8dSArtem Dergachev     }
133612294f8dSArtem Dergachev 
133712294f8dSArtem Dergachev     SVal VisitSVal(SVal V) { return V; }
133812294f8dSArtem Dergachev   };
133912294f8dSArtem Dergachev 
134016a1f64cSArtem Dergachev   // A crude way of preventing this function from calling itself from evalBinOp.
134116a1f64cSArtem Dergachev   static bool isReentering = false;
134216a1f64cSArtem Dergachev   if (isReentering)
134316a1f64cSArtem Dergachev     return V;
134416a1f64cSArtem Dergachev 
134516a1f64cSArtem Dergachev   isReentering = true;
134616a1f64cSArtem Dergachev   SVal SimplifiedV = Simplifier(State).Visit(V);
134716a1f64cSArtem Dergachev   isReentering = false;
134816a1f64cSArtem Dergachev 
134916a1f64cSArtem Dergachev   return SimplifiedV;
135012294f8dSArtem Dergachev }
1351