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