Coverage Report

Created: 2019-07-24 05:18

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