SimpleSValBuilder.cpp revision 732cdf383f9030ff2b9fb28dfbdae2285ded80c6
1// SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- C++ -*-
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines SimpleSValBuilder, a basic implementation of SValBuilder.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
15#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
16#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
17
18using namespace clang;
19using namespace ento;
20
21namespace {
22class SimpleSValBuilder : public SValBuilder {
23protected:
24  virtual SVal dispatchCast(SVal val, QualType castTy);
25  virtual SVal evalCastFromNonLoc(NonLoc val, QualType castTy);
26  virtual SVal evalCastFromLoc(Loc val, QualType castTy);
27
28public:
29  SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
30                    ProgramStateManager &stateMgr)
31                    : SValBuilder(alloc, context, stateMgr) {}
32  virtual ~SimpleSValBuilder() {}
33
34  virtual SVal evalMinus(NonLoc val);
35  virtual SVal evalComplement(NonLoc val);
36  virtual SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
37                           NonLoc lhs, NonLoc rhs, QualType resultTy);
38  virtual SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
39                           Loc lhs, Loc rhs, QualType resultTy);
40  virtual SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
41                           Loc lhs, NonLoc rhs, QualType resultTy);
42
43  /// getKnownValue - evaluates a given SVal. If the SVal has only one possible
44  ///  (integer) value, that value is returned. Otherwise, returns NULL.
45  virtual const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V);
46
47  SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
48                     const llvm::APSInt &RHS, QualType resultTy);
49};
50} // end anonymous namespace
51
52SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
53                                           ASTContext &context,
54                                           ProgramStateManager &stateMgr) {
55  return new SimpleSValBuilder(alloc, context, stateMgr);
56}
57
58//===----------------------------------------------------------------------===//
59// Transfer function for Casts.
60//===----------------------------------------------------------------------===//
61
62SVal SimpleSValBuilder::dispatchCast(SVal Val, QualType CastTy) {
63  assert(isa<Loc>(&Val) || isa<NonLoc>(&Val));
64  return isa<Loc>(Val) ? evalCastFromLoc(cast<Loc>(Val), CastTy)
65                       : evalCastFromNonLoc(cast<NonLoc>(Val), CastTy);
66}
67
68SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
69
70  bool isLocType = Loc::isLocType(castTy);
71
72  if (nonloc::LocAsInteger *LI = dyn_cast<nonloc::LocAsInteger>(&val)) {
73    if (isLocType)
74      return LI->getLoc();
75
76    // FIXME: Correctly support promotions/truncations.
77    unsigned castSize = Context.getTypeSize(castTy);
78    if (castSize == LI->getNumBits())
79      return val;
80    return makeLocAsInteger(LI->getLoc(), castSize);
81  }
82
83  if (const SymExpr *se = val.getAsSymbolicExpression()) {
84    QualType T = Context.getCanonicalType(se->getType());
85    // If types are the same or both are integers, ignore the cast.
86    // FIXME: Remove this hack when we support symbolic truncation/extension.
87    // HACK: If both castTy and T are integers, ignore the cast.  This is
88    // not a permanent solution.  Eventually we want to precisely handle
89    // extension/truncation of symbolic integers.  This prevents us from losing
90    // precision when we assign 'x = y' and 'y' is symbolic and x and y are
91    // different integer types.
92   if (haveSameType(T, castTy))
93      return val;
94
95    if (!isLocType)
96      return makeNonLoc(se, T, castTy);
97    return UnknownVal();
98  }
99
100  // If value is a non integer constant, produce unknown.
101  if (!isa<nonloc::ConcreteInt>(val))
102    return UnknownVal();
103
104  // Only handle casts from integers to integers - if val is an integer constant
105  // being cast to a non integer type, produce unknown.
106  if (!isLocType && !castTy->isIntegerType())
107    return UnknownVal();
108
109  llvm::APSInt i = cast<nonloc::ConcreteInt>(val).getValue();
110  BasicVals.getAPSIntType(castTy).apply(i);
111
112  if (isLocType)
113    return makeIntLocVal(i);
114  else
115    return makeIntVal(i);
116}
117
118SVal SimpleSValBuilder::evalCastFromLoc(Loc val, QualType castTy) {
119
120  // Casts from pointers -> pointers, just return the lval.
121  //
122  // Casts from pointers -> references, just return the lval.  These
123  //   can be introduced by the frontend for corner cases, e.g
124  //   casting from va_list* to __builtin_va_list&.
125  //
126  if (Loc::isLocType(castTy) || castTy->isReferenceType())
127    return val;
128
129  // FIXME: Handle transparent unions where a value can be "transparently"
130  //  lifted into a union type.
131  if (castTy->isUnionType())
132    return UnknownVal();
133
134  if (castTy->isIntegerType()) {
135    unsigned BitWidth = Context.getTypeSize(castTy);
136
137    if (!isa<loc::ConcreteInt>(val))
138      return makeLocAsInteger(val, BitWidth);
139
140    llvm::APSInt i = cast<loc::ConcreteInt>(val).getValue();
141    BasicVals.getAPSIntType(castTy).apply(i);
142    return makeIntVal(i);
143  }
144
145  // All other cases: return 'UnknownVal'.  This includes casting pointers
146  // to floats, which is probably badness it itself, but this is a good
147  // intermediate solution until we do something better.
148  return UnknownVal();
149}
150
151//===----------------------------------------------------------------------===//
152// Transfer function for unary operators.
153//===----------------------------------------------------------------------===//
154
155SVal SimpleSValBuilder::evalMinus(NonLoc val) {
156  switch (val.getSubKind()) {
157  case nonloc::ConcreteIntKind:
158    return cast<nonloc::ConcreteInt>(val).evalMinus(*this);
159  default:
160    return UnknownVal();
161  }
162}
163
164SVal SimpleSValBuilder::evalComplement(NonLoc X) {
165  switch (X.getSubKind()) {
166  case nonloc::ConcreteIntKind:
167    return cast<nonloc::ConcreteInt>(X).evalComplement(*this);
168  default:
169    return UnknownVal();
170  }
171}
172
173//===----------------------------------------------------------------------===//
174// Transfer function for binary operators.
175//===----------------------------------------------------------------------===//
176
177static BinaryOperator::Opcode NegateComparison(BinaryOperator::Opcode op) {
178  switch (op) {
179  default:
180    llvm_unreachable("Invalid opcode.");
181  case BO_LT: return BO_GE;
182  case BO_GT: return BO_LE;
183  case BO_LE: return BO_GT;
184  case BO_GE: return BO_LT;
185  case BO_EQ: return BO_NE;
186  case BO_NE: return BO_EQ;
187  }
188}
189
190static BinaryOperator::Opcode ReverseComparison(BinaryOperator::Opcode op) {
191  switch (op) {
192  default:
193    llvm_unreachable("Invalid opcode.");
194  case BO_LT: return BO_GT;
195  case BO_GT: return BO_LT;
196  case BO_LE: return BO_GE;
197  case BO_GE: return BO_LE;
198  case BO_EQ:
199  case BO_NE:
200    return op;
201  }
202}
203
204SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
205                                    BinaryOperator::Opcode op,
206                                    const llvm::APSInt &RHS,
207                                    QualType resultTy) {
208  bool isIdempotent = false;
209
210  // Check for a few special cases with known reductions first.
211  switch (op) {
212  default:
213    // We can't reduce this case; just treat it normally.
214    break;
215  case BO_Mul:
216    // a*0 and a*1
217    if (RHS == 0)
218      return makeIntVal(0, resultTy);
219    else if (RHS == 1)
220      isIdempotent = true;
221    break;
222  case BO_Div:
223    // a/0 and a/1
224    if (RHS == 0)
225      // This is also handled elsewhere.
226      return UndefinedVal();
227    else if (RHS == 1)
228      isIdempotent = true;
229    break;
230  case BO_Rem:
231    // a%0 and a%1
232    if (RHS == 0)
233      // This is also handled elsewhere.
234      return UndefinedVal();
235    else if (RHS == 1)
236      return makeIntVal(0, resultTy);
237    break;
238  case BO_Add:
239  case BO_Sub:
240  case BO_Shl:
241  case BO_Shr:
242  case BO_Xor:
243    // a+0, a-0, a<<0, a>>0, a^0
244    if (RHS == 0)
245      isIdempotent = true;
246    break;
247  case BO_And:
248    // a&0 and a&(~0)
249    if (RHS == 0)
250      return makeIntVal(0, resultTy);
251    else if (RHS.isAllOnesValue())
252      isIdempotent = true;
253    break;
254  case BO_Or:
255    // a|0 and a|(~0)
256    if (RHS == 0)
257      isIdempotent = true;
258    else if (RHS.isAllOnesValue()) {
259      const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
260      return nonloc::ConcreteInt(Result);
261    }
262    break;
263  }
264
265  // Idempotent ops (like a*1) can still change the type of an expression.
266  // Wrap the LHS up in a NonLoc again and let evalCastFromNonLoc do the
267  // dirty work.
268  if (isIdempotent)
269      return evalCastFromNonLoc(nonloc::SymbolVal(LHS), resultTy);
270
271  // If we reach this point, the expression cannot be simplified.
272  // Make a SymbolVal for the entire expression, after converting the RHS.
273  const llvm::APSInt *ConvertedRHS = &RHS;
274  if (BinaryOperator::isComparisonOp(op)) {
275    // We're looking for a type big enough to compare the symbolic value
276    // with the given constant.
277    // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
278    ASTContext &Ctx = getContext();
279    QualType SymbolType = LHS->getType();
280    uint64_t ValWidth = RHS.getBitWidth();
281    uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
282
283    if (ValWidth < TypeWidth) {
284      // If the value is too small, extend it.
285      ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
286    } else if (ValWidth == TypeWidth) {
287      // If the value is signed but the symbol is unsigned, do the comparison
288      // in unsigned space. [C99 6.3.1.8]
289      // (For the opposite case, the value is already unsigned.)
290      if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
291        ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
292    }
293  } else
294    ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
295
296  return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
297}
298
299SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
300                                  BinaryOperator::Opcode op,
301                                  NonLoc lhs, NonLoc rhs,
302                                  QualType resultTy)  {
303  NonLoc InputLHS = lhs;
304  NonLoc InputRHS = rhs;
305
306  // Handle trivial case where left-side and right-side are the same.
307  if (lhs == rhs)
308    switch (op) {
309      default:
310        break;
311      case BO_EQ:
312      case BO_LE:
313      case BO_GE:
314        return makeTruthVal(true, resultTy);
315      case BO_LT:
316      case BO_GT:
317      case BO_NE:
318        return makeTruthVal(false, resultTy);
319      case BO_Xor:
320      case BO_Sub:
321        if (resultTy->isIntegralOrEnumerationType())
322          return makeIntVal(0, resultTy);
323        return evalCastFromNonLoc(makeIntVal(0, /*Unsigned=*/false), resultTy);
324      case BO_Or:
325      case BO_And:
326        return evalCastFromNonLoc(lhs, resultTy);
327    }
328
329  while (1) {
330    switch (lhs.getSubKind()) {
331    default:
332      return makeSymExprValNN(state, op, lhs, rhs, resultTy);
333    case nonloc::LocAsIntegerKind: {
334      Loc lhsL = cast<nonloc::LocAsInteger>(lhs).getLoc();
335      switch (rhs.getSubKind()) {
336        case nonloc::LocAsIntegerKind:
337          return evalBinOpLL(state, op, lhsL,
338                             cast<nonloc::LocAsInteger>(rhs).getLoc(),
339                             resultTy);
340        case nonloc::ConcreteIntKind: {
341          // Transform the integer into a location and compare.
342          llvm::APSInt i = cast<nonloc::ConcreteInt>(rhs).getValue();
343          BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
344          return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
345        }
346        default:
347          switch (op) {
348            case BO_EQ:
349              return makeTruthVal(false, resultTy);
350            case BO_NE:
351              return makeTruthVal(true, resultTy);
352            default:
353              // This case also handles pointer arithmetic.
354              return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
355          }
356      }
357    }
358    case nonloc::ConcreteIntKind: {
359      llvm::APSInt LHSValue = cast<nonloc::ConcreteInt>(lhs).getValue();
360
361      // If we're dealing with two known constants, just perform the operation.
362      if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) {
363        llvm::APSInt RHSValue = *KnownRHSValue;
364        if (BinaryOperator::isComparisonOp(op)) {
365          // We're looking for a type big enough to compare the two values.
366          // FIXME: This is not correct. char + short will result in a promotion
367          // to int. Unfortunately we have lost types by this point.
368          APSIntType CompareType = std::max(APSIntType(LHSValue),
369                                            APSIntType(RHSValue));
370          CompareType.apply(LHSValue);
371          CompareType.apply(RHSValue);
372        } else if (!BinaryOperator::isShiftOp(op)) {
373          APSIntType IntType = BasicVals.getAPSIntType(resultTy);
374          IntType.apply(LHSValue);
375          IntType.apply(RHSValue);
376        }
377
378        const llvm::APSInt *Result =
379          BasicVals.evalAPSInt(op, LHSValue, RHSValue);
380        if (!Result)
381          return UndefinedVal();
382
383        return nonloc::ConcreteInt(*Result);
384      }
385
386      // Swap the left and right sides and flip the operator if doing so
387      // allows us to better reason about the expression (this is a form
388      // of expression canonicalization).
389      // While we're at it, catch some special cases for non-commutative ops.
390      switch (op) {
391      case BO_LT:
392      case BO_GT:
393      case BO_LE:
394      case BO_GE:
395        op = ReverseComparison(op);
396        // FALL-THROUGH
397      case BO_EQ:
398      case BO_NE:
399      case BO_Add:
400      case BO_Mul:
401      case BO_And:
402      case BO_Xor:
403      case BO_Or:
404        std::swap(lhs, rhs);
405        continue;
406      case BO_Shr:
407        // (~0)>>a
408        if (LHSValue.isAllOnesValue() && LHSValue.isSigned())
409          return evalCastFromNonLoc(lhs, resultTy);
410        // FALL-THROUGH
411      case BO_Shl:
412        // 0<<a and 0>>a
413        if (LHSValue == 0)
414          return evalCastFromNonLoc(lhs, resultTy);
415        return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
416      default:
417        return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
418      }
419    }
420    case nonloc::SymbolValKind: {
421      // We only handle LHS as simple symbols or SymIntExprs.
422      SymbolRef Sym = cast<nonloc::SymbolVal>(lhs).getSymbol();
423
424      // LHS is a symbolic expression.
425      if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
426
427        // Is this a logical not? (!x is represented as x == 0.)
428        if (op == BO_EQ && rhs.isZeroConstant()) {
429          // We know how to negate certain expressions. Simplify them here.
430
431          BinaryOperator::Opcode opc = symIntExpr->getOpcode();
432          switch (opc) {
433          default:
434            // We don't know how to negate this operation.
435            // Just handle it as if it were a normal comparison to 0.
436            break;
437          case BO_LAnd:
438          case BO_LOr:
439            llvm_unreachable("Logical operators handled by branching logic.");
440          case BO_Assign:
441          case BO_MulAssign:
442          case BO_DivAssign:
443          case BO_RemAssign:
444          case BO_AddAssign:
445          case BO_SubAssign:
446          case BO_ShlAssign:
447          case BO_ShrAssign:
448          case BO_AndAssign:
449          case BO_XorAssign:
450          case BO_OrAssign:
451          case BO_Comma:
452            llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
453          case BO_PtrMemD:
454          case BO_PtrMemI:
455            llvm_unreachable("Pointer arithmetic not handled here.");
456          case BO_LT:
457          case BO_GT:
458          case BO_LE:
459          case BO_GE:
460          case BO_EQ:
461          case BO_NE:
462            // Negate the comparison and make a value.
463            opc = NegateComparison(opc);
464            assert(symIntExpr->getType() == resultTy);
465            return makeNonLoc(symIntExpr->getLHS(), opc,
466                symIntExpr->getRHS(), resultTy);
467          }
468        }
469
470        // For now, only handle expressions whose RHS is a constant.
471        if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) {
472          // If both the LHS and the current expression are additive,
473          // fold their constants and try again.
474          if (BinaryOperator::isAdditiveOp(op)) {
475            BinaryOperator::Opcode lop = symIntExpr->getOpcode();
476            if (BinaryOperator::isAdditiveOp(lop)) {
477              // Convert the two constants to a common type, then combine them.
478
479              // resultTy may not be the best type to convert to, but it's
480              // probably the best choice in expressions with mixed type
481              // (such as x+1U+2LL). The rules for implicit conversions should
482              // choose a reasonable type to preserve the expression, and will
483              // at least match how the value is going to be used.
484              APSIntType IntType = BasicVals.getAPSIntType(resultTy);
485              const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
486              const llvm::APSInt &second = IntType.convert(*RHSValue);
487
488              const llvm::APSInt *newRHS;
489              if (lop == op)
490                newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
491              else
492                newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
493
494              assert(newRHS && "Invalid operation despite common type!");
495              rhs = nonloc::ConcreteInt(*newRHS);
496              lhs = nonloc::SymbolVal(symIntExpr->getLHS());
497              op = lop;
498              continue;
499            }
500          }
501
502          // Otherwise, make a SymIntExpr out of the expression.
503          return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
504        }
505
506
507      } else if (isa<SymbolData>(Sym)) {
508        // Does the symbol simplify to a constant?  If so, "fold" the constant
509        // by setting 'lhs' to a ConcreteInt and try again.
510        if (const llvm::APSInt *Constant = state->getConstraintManager()
511                                                  .getSymVal(state, Sym)) {
512          lhs = nonloc::ConcreteInt(*Constant);
513          continue;
514        }
515
516        // Is the RHS a constant?
517        if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
518          return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
519      }
520
521      // Give up -- this is not a symbolic expression we can handle.
522      return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
523    }
524    }
525  }
526}
527
528// FIXME: all this logic will change if/when we have MemRegion::getLocation().
529SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
530                                  BinaryOperator::Opcode op,
531                                  Loc lhs, Loc rhs,
532                                  QualType resultTy) {
533  // Only comparisons and subtractions are valid operations on two pointers.
534  // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
535  // However, if a pointer is casted to an integer, evalBinOpNN may end up
536  // calling this function with another operation (PR7527). We don't attempt to
537  // model this for now, but it could be useful, particularly when the
538  // "location" is actually an integer value that's been passed through a void*.
539  if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
540    return UnknownVal();
541
542  // Special cases for when both sides are identical.
543  if (lhs == rhs) {
544    switch (op) {
545    default:
546      llvm_unreachable("Unimplemented operation for two identical values");
547    case BO_Sub:
548      return makeZeroVal(resultTy);
549    case BO_EQ:
550    case BO_LE:
551    case BO_GE:
552      return makeTruthVal(true, resultTy);
553    case BO_NE:
554    case BO_LT:
555    case BO_GT:
556      return makeTruthVal(false, resultTy);
557    }
558  }
559
560  switch (lhs.getSubKind()) {
561  default:
562    llvm_unreachable("Ordering not implemented for this Loc.");
563
564  case loc::GotoLabelKind:
565    // The only thing we know about labels is that they're non-null.
566    if (rhs.isZeroConstant()) {
567      switch (op) {
568      default:
569        break;
570      case BO_Sub:
571        return evalCastFromLoc(lhs, resultTy);
572      case BO_EQ:
573      case BO_LE:
574      case BO_LT:
575        return makeTruthVal(false, resultTy);
576      case BO_NE:
577      case BO_GT:
578      case BO_GE:
579        return makeTruthVal(true, resultTy);
580      }
581    }
582    // There may be two labels for the same location, and a function region may
583    // have the same address as a label at the start of the function (depending
584    // on the ABI).
585    // FIXME: we can probably do a comparison against other MemRegions, though.
586    // FIXME: is there a way to tell if two labels refer to the same location?
587    return UnknownVal();
588
589  case loc::ConcreteIntKind: {
590    // If one of the operands is a symbol and the other is a constant,
591    // build an expression for use by the constraint manager.
592    if (SymbolRef rSym = rhs.getAsLocSymbol()) {
593      // We can only build expressions with symbols on the left,
594      // so we need a reversible operator.
595      if (!BinaryOperator::isComparisonOp(op))
596        return UnknownVal();
597
598      const llvm::APSInt &lVal = cast<loc::ConcreteInt>(lhs).getValue();
599      return makeNonLoc(rSym, ReverseComparison(op), lVal, resultTy);
600    }
601
602    // If both operands are constants, just perform the operation.
603    if (loc::ConcreteInt *rInt = dyn_cast<loc::ConcreteInt>(&rhs)) {
604      SVal ResultVal = cast<loc::ConcreteInt>(lhs).evalBinOp(BasicVals, op,
605                                                             *rInt);
606      if (Loc *Result = dyn_cast<Loc>(&ResultVal))
607        return evalCastFromLoc(*Result, resultTy);
608      else
609        return UnknownVal();
610    }
611
612    // Special case comparisons against NULL.
613    // This must come after the test if the RHS is a symbol, which is used to
614    // build constraints. The address of any non-symbolic region is guaranteed
615    // to be non-NULL, as is any label.
616    assert(isa<loc::MemRegionVal>(rhs) || isa<loc::GotoLabel>(rhs));
617    if (lhs.isZeroConstant()) {
618      switch (op) {
619      default:
620        break;
621      case BO_EQ:
622      case BO_GT:
623      case BO_GE:
624        return makeTruthVal(false, resultTy);
625      case BO_NE:
626      case BO_LT:
627      case BO_LE:
628        return makeTruthVal(true, resultTy);
629      }
630    }
631
632    // Comparing an arbitrary integer to a region or label address is
633    // completely unknowable.
634    return UnknownVal();
635  }
636  case loc::MemRegionKind: {
637    if (loc::ConcreteInt *rInt = dyn_cast<loc::ConcreteInt>(&rhs)) {
638      // If one of the operands is a symbol and the other is a constant,
639      // build an expression for use by the constraint manager.
640      if (SymbolRef lSym = lhs.getAsLocSymbol())
641        return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
642
643      // Special case comparisons to NULL.
644      // This must come after the test if the LHS is a symbol, which is used to
645      // build constraints. The address of any non-symbolic region is guaranteed
646      // to be non-NULL.
647      if (rInt->isZeroConstant()) {
648        switch (op) {
649        default:
650          break;
651        case BO_Sub:
652          return evalCastFromLoc(lhs, resultTy);
653        case BO_EQ:
654        case BO_LT:
655        case BO_LE:
656          return makeTruthVal(false, resultTy);
657        case BO_NE:
658        case BO_GT:
659        case BO_GE:
660          return makeTruthVal(true, resultTy);
661        }
662      }
663
664      // Comparing a region to an arbitrary integer is completely unknowable.
665      return UnknownVal();
666    }
667
668    // Get both values as regions, if possible.
669    const MemRegion *LeftMR = lhs.getAsRegion();
670    assert(LeftMR && "MemRegionKind SVal doesn't have a region!");
671
672    const MemRegion *RightMR = rhs.getAsRegion();
673    if (!RightMR)
674      // The RHS is probably a label, which in theory could address a region.
675      // FIXME: we can probably make a more useful statement about non-code
676      // regions, though.
677      return UnknownVal();
678
679    const MemSpaceRegion *LeftMS = LeftMR->getMemorySpace();
680    const MemSpaceRegion *RightMS = RightMR->getMemorySpace();
681    const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
682    const MemRegion *LeftBase = LeftMR->getBaseRegion();
683    const MemRegion *RightBase = RightMR->getBaseRegion();
684
685    // If the two regions are from different known memory spaces they cannot be
686    // equal. Also, assume that no symbolic region (whose memory space is
687    // unknown) is on the stack.
688    if (LeftMS != RightMS &&
689        ((LeftMS != UnknownMS && RightMS != UnknownMS) ||
690         (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
691      switch (op) {
692      default:
693        return UnknownVal();
694      case BO_EQ:
695        return makeTruthVal(false, resultTy);
696      case BO_NE:
697        return makeTruthVal(true, resultTy);
698      }
699    }
700
701    // If both values wrap regions, see if they're from different base regions.
702    // Note, heap base symbolic regions are assumed to not alias with
703    // each other; for example, we assume that malloc returns different address
704    // on each invocation.
705    if (LeftBase != RightBase &&
706        ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
707         (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
708      switch (op) {
709      default:
710        return UnknownVal();
711      case BO_EQ:
712        return makeTruthVal(false, resultTy);
713      case BO_NE:
714        return makeTruthVal(true, resultTy);
715      }
716    }
717
718    // FIXME: If/when there is a getAsRawOffset() for FieldRegions, this
719    // ElementRegion path and the FieldRegion path below should be unified.
720    if (const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR)) {
721      // First see if the right region is also an ElementRegion.
722      const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
723      if (!RightER)
724        return UnknownVal();
725
726      // Next, see if the two ERs have the same super-region and matching types.
727      // FIXME: This should do something useful even if the types don't match,
728      // though if both indexes are constant the RegionRawOffset path will
729      // give the correct answer.
730      if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
731          LeftER->getElementType() == RightER->getElementType()) {
732        // Get the left index and cast it to the correct type.
733        // If the index is unknown or undefined, bail out here.
734        SVal LeftIndexVal = LeftER->getIndex();
735        NonLoc *LeftIndex = dyn_cast<NonLoc>(&LeftIndexVal);
736        if (!LeftIndex)
737          return UnknownVal();
738        LeftIndexVal = evalCastFromNonLoc(*LeftIndex, resultTy);
739        LeftIndex = dyn_cast<NonLoc>(&LeftIndexVal);
740        if (!LeftIndex)
741          return UnknownVal();
742
743        // Do the same for the right index.
744        SVal RightIndexVal = RightER->getIndex();
745        NonLoc *RightIndex = dyn_cast<NonLoc>(&RightIndexVal);
746        if (!RightIndex)
747          return UnknownVal();
748        RightIndexVal = evalCastFromNonLoc(*RightIndex, resultTy);
749        RightIndex = dyn_cast<NonLoc>(&RightIndexVal);
750        if (!RightIndex)
751          return UnknownVal();
752
753        // Actually perform the operation.
754        // evalBinOpNN expects the two indexes to already be the right type.
755        return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
756      }
757
758      // If the element indexes aren't comparable, see if the raw offsets are.
759      RegionRawOffset LeftOffset = LeftER->getAsArrayOffset();
760      RegionRawOffset RightOffset = RightER->getAsArrayOffset();
761
762      if (LeftOffset.getRegion() != NULL &&
763          LeftOffset.getRegion() == RightOffset.getRegion()) {
764        CharUnits left = LeftOffset.getOffset();
765        CharUnits right = RightOffset.getOffset();
766
767        switch (op) {
768        default:
769          return UnknownVal();
770        case BO_LT:
771          return makeTruthVal(left < right, resultTy);
772        case BO_GT:
773          return makeTruthVal(left > right, resultTy);
774        case BO_LE:
775          return makeTruthVal(left <= right, resultTy);
776        case BO_GE:
777          return makeTruthVal(left >= right, resultTy);
778        case BO_EQ:
779          return makeTruthVal(left == right, resultTy);
780        case BO_NE:
781          return makeTruthVal(left != right, resultTy);
782        }
783      }
784
785      // If we get here, we have no way of comparing the ElementRegions.
786      return UnknownVal();
787    }
788
789    // See if both regions are fields of the same structure.
790    // FIXME: This doesn't handle nesting, inheritance, or Objective-C ivars.
791    if (const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR)) {
792      // Only comparisons are meaningful here!
793      if (!BinaryOperator::isComparisonOp(op))
794        return UnknownVal();
795
796      // First see if the right region is also a FieldRegion.
797      const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
798      if (!RightFR)
799        return UnknownVal();
800
801      // Next, see if the two FRs have the same super-region.
802      // FIXME: This doesn't handle casts yet, and simply stripping the casts
803      // doesn't help.
804      if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
805        return UnknownVal();
806
807      const FieldDecl *LeftFD = LeftFR->getDecl();
808      const FieldDecl *RightFD = RightFR->getDecl();
809      const RecordDecl *RD = LeftFD->getParent();
810
811      // Make sure the two FRs are from the same kind of record. Just in case!
812      // FIXME: This is probably where inheritance would be a problem.
813      if (RD != RightFD->getParent())
814        return UnknownVal();
815
816      // We know for sure that the two fields are not the same, since that
817      // would have given us the same SVal.
818      if (op == BO_EQ)
819        return makeTruthVal(false, resultTy);
820      if (op == BO_NE)
821        return makeTruthVal(true, resultTy);
822
823      // Iterate through the fields and see which one comes first.
824      // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
825      // members and the units in which bit-fields reside have addresses that
826      // increase in the order in which they are declared."
827      bool leftFirst = (op == BO_LT || op == BO_LE);
828      for (RecordDecl::field_iterator I = RD->field_begin(),
829           E = RD->field_end(); I!=E; ++I) {
830        if (*I == LeftFD)
831          return makeTruthVal(leftFirst, resultTy);
832        if (*I == RightFD)
833          return makeTruthVal(!leftFirst, resultTy);
834      }
835
836      llvm_unreachable("Fields not found in parent record's definition");
837    }
838
839    // If we get here, we have no way of comparing the regions.
840    return UnknownVal();
841  }
842  }
843}
844
845SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
846                                  BinaryOperator::Opcode op,
847                                  Loc lhs, NonLoc rhs, QualType resultTy) {
848
849  // Special case: rhs is a zero constant.
850  if (rhs.isZeroConstant())
851    return lhs;
852
853  // Special case: 'rhs' is an integer that has the same width as a pointer and
854  // we are using the integer location in a comparison.  Normally this cannot be
855  // triggered, but transfer functions like those for OSCommpareAndSwapBarrier32
856  // can generate comparisons that trigger this code.
857  // FIXME: Are all locations guaranteed to have pointer width?
858  if (BinaryOperator::isComparisonOp(op)) {
859    if (nonloc::ConcreteInt *rhsInt = dyn_cast<nonloc::ConcreteInt>(&rhs)) {
860      const llvm::APSInt *x = &rhsInt->getValue();
861      ASTContext &ctx = Context;
862      if (ctx.getTypeSize(ctx.VoidPtrTy) == x->getBitWidth()) {
863        // Convert the signedness of the integer (if necessary).
864        if (x->isSigned())
865          x = &getBasicValueFactory().getValue(*x, true);
866
867        return evalBinOpLL(state, op, lhs, loc::ConcreteInt(*x), resultTy);
868      }
869    }
870    return UnknownVal();
871  }
872
873  // We are dealing with pointer arithmetic.
874
875  // Handle pointer arithmetic on constant values.
876  if (nonloc::ConcreteInt *rhsInt = dyn_cast<nonloc::ConcreteInt>(&rhs)) {
877    if (loc::ConcreteInt *lhsInt = dyn_cast<loc::ConcreteInt>(&lhs)) {
878      const llvm::APSInt &leftI = lhsInt->getValue();
879      assert(leftI.isUnsigned());
880      llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
881
882      // Convert the bitwidth of rightI.  This should deal with overflow
883      // since we are dealing with concrete values.
884      rightI = rightI.extOrTrunc(leftI.getBitWidth());
885
886      // Offset the increment by the pointer size.
887      llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
888      rightI *= Multiplicand;
889
890      // Compute the adjusted pointer.
891      switch (op) {
892        case BO_Add:
893          rightI = leftI + rightI;
894          break;
895        case BO_Sub:
896          rightI = leftI - rightI;
897          break;
898        default:
899          llvm_unreachable("Invalid pointer arithmetic operation");
900      }
901      return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
902    }
903  }
904
905  // Handle cases where 'lhs' is a region.
906  if (const MemRegion *region = lhs.getAsRegion()) {
907    rhs = cast<NonLoc>(convertToArrayIndex(rhs));
908    SVal index = UnknownVal();
909    const MemRegion *superR = 0;
910    QualType elementType;
911
912    if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
913      assert(op == BO_Add || op == BO_Sub);
914      index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
915                          getArrayIndexType());
916      superR = elemReg->getSuperRegion();
917      elementType = elemReg->getElementType();
918    }
919    else if (isa<SubRegion>(region)) {
920      superR = region;
921      index = rhs;
922      if (resultTy->isAnyPointerType())
923        elementType = resultTy->getPointeeType();
924    }
925
926    if (NonLoc *indexV = dyn_cast<NonLoc>(&index)) {
927      return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
928                                                       superR, getContext()));
929    }
930  }
931  return UnknownVal();
932}
933
934const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
935                                                   SVal V) {
936  if (V.isUnknownOrUndef())
937    return NULL;
938
939  if (loc::ConcreteInt* X = dyn_cast<loc::ConcreteInt>(&V))
940    return &X->getValue();
941
942  if (nonloc::ConcreteInt* X = dyn_cast<nonloc::ConcreteInt>(&V))
943    return &X->getValue();
944
945  if (SymbolRef Sym = V.getAsSymbol())
946    return state->getConstraintManager().getSymVal(state, Sym);
947
948  // FIXME: Add support for SymExprs.
949  return NULL;
950}
951