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