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