Coverage Report

Created: 2023-09-21 18:56

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