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