#include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h"
using namespace clang;
using namespace ento;
namespace {
class SimpleSValBuilder : public SValBuilder {
const llvm::APSInt *getConstValue(ProgramStateRef state, SVal V);
SVal simplifyUntilFixpoint(ProgramStateRef State, SVal Val);
SVal simplifySValOnce(ProgramStateRef State, SVal V);
public:
SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
ProgramStateManager &stateMgr)
: SValBuilder(alloc, context, stateMgr) {}
~SimpleSValBuilder() override {}
SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
NonLoc lhs, NonLoc rhs, QualType resultTy) override;
SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
Loc lhs, Loc rhs, QualType resultTy) override;
SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
Loc lhs, NonLoc rhs, QualType resultTy) override;
const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override;
SVal simplifySVal(ProgramStateRef State, SVal V) override;
SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
const llvm::APSInt &RHS, QualType resultTy);
};
}
SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
ASTContext &context,
ProgramStateManager &stateMgr) {
return new SimpleSValBuilder(alloc, context, stateMgr);
}
static bool isNegationValuePreserving(const llvm::APSInt &Value,
APSIntType ResultType) {
const unsigned ValueBits = Value.getSignificantBits();
if (ValueBits == ResultType.getBitWidth()) {
return ResultType.isUnsigned();
}
return ValueBits < ResultType.getBitWidth();
}
SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
BinaryOperator::Opcode op,
const llvm::APSInt &RHS,
QualType resultTy) {
bool isIdempotent = false;
switch (op) {
default:
break;
case BO_Mul:
if (RHS == 0)
return makeIntVal(0, resultTy);
else if (RHS == 1)
isIdempotent = true;
break;
case BO_Div:
if (RHS == 0)
return UndefinedVal();
else if (RHS == 1)
isIdempotent = true;
break;
case BO_Rem:
if (RHS == 0)
return UndefinedVal();
else if (RHS == 1)
return makeIntVal(0, resultTy);
break;
case BO_Add:
case BO_Sub:
case BO_Shl:
case BO_Shr:
case BO_Xor:
if (RHS == 0)
isIdempotent = true;
break;
case BO_And:
if (RHS == 0)
return makeIntVal(0, resultTy);
else if (RHS.isAllOnes())
isIdempotent = true;
break;
case BO_Or:
if (RHS == 0)
isIdempotent = true;
else if (RHS.isAllOnes()) {
const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
return nonloc::ConcreteInt(Result);
}
break;
}
if (isIdempotent)
return evalCast(nonloc::SymbolVal(LHS), resultTy, QualType{});
const llvm::APSInt *ConvertedRHS = &RHS;
if (BinaryOperator::isComparisonOp(op)) {
ASTContext &Ctx = getContext();
QualType SymbolType = LHS->getType();
uint64_t ValWidth = RHS.getBitWidth();
uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
if (ValWidth < TypeWidth) {
ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
} else if (ValWidth == TypeWidth) {
if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
}
} else if (BinaryOperator::isAdditiveOp(op) && RHS.isNegative()) {
APSIntType resultIntTy = BasicVals.getAPSIntType(resultTy);
if (isNegationValuePreserving(RHS, resultIntTy)) {
ConvertedRHS = &BasicVals.getValue(-resultIntTy.convert(RHS));
op = (op == BO_Add) ? BO_Sub : BO_Add;
} else {
ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
}
} else
ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
}
static bool isInRelation(BinaryOperator::Opcode Rel, SymbolRef Sym,
llvm::APSInt Bound, ProgramStateRef State) {
SValBuilder &SVB = State->getStateManager().getSValBuilder();
SVal Result =
SVB.evalBinOpNN(State, Rel, nonloc::SymbolVal(Sym),
nonloc::ConcreteInt(Bound), SVB.getConditionType());
if (auto DV = Result.getAs<DefinedSVal>()) {
return !State->assume(*DV, false);
}
return false;
}
static bool isWithinConstantOverflowBounds(SymbolRef Sym,
ProgramStateRef State) {
SValBuilder &SVB = State->getStateManager().getSValBuilder();
BasicValueFactory &BV = SVB.getBasicValueFactory();
QualType T = Sym->getType();
assert(T->isSignedIntegerOrEnumerationType() &&
"This only works with signed integers!");
APSIntType AT = BV.getAPSIntType(T);
llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
return isInRelation(BO_LE, Sym, Max, State) &&
isInRelation(BO_GE, Sym, Min, State);
}
static bool isWithinConstantOverflowBounds(llvm::APSInt I) {
APSIntType AT(I);
assert(!AT.isUnsigned() &&
"This only works with signed integers!");
llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max;
return (I <= Max) && (I >= -Max);
}
static std::pair<SymbolRef, llvm::APSInt>
decomposeSymbol(SymbolRef Sym, BasicValueFactory &BV) {
if (const auto *SymInt = dyn_cast<SymIntExpr>(Sym))
if (BinaryOperator::isAdditiveOp(SymInt->getOpcode()))
return std::make_pair(SymInt->getLHS(),
(SymInt->getOpcode() == BO_Add) ?
(SymInt->getRHS()) :
(-SymInt->getRHS()));
return std::make_pair(Sym, BV.getValue(0, Sym->getType()));
}
static NonLoc doRearrangeUnchecked(ProgramStateRef State,
BinaryOperator::Opcode Op,
SymbolRef LSym, llvm::APSInt LInt,
SymbolRef RSym, llvm::APSInt RInt) {
SValBuilder &SVB = State->getStateManager().getSValBuilder();
BasicValueFactory &BV = SVB.getBasicValueFactory();
SymbolManager &SymMgr = SVB.getSymbolManager();
QualType SymTy = LSym->getType();
assert(SymTy == RSym->getType() &&
"Symbols are not of the same type!");
assert(APSIntType(LInt) == BV.getAPSIntType(SymTy) &&
"Integers are not of the same type as symbols!");
assert(APSIntType(RInt) == BV.getAPSIntType(SymTy) &&
"Integers are not of the same type as symbols!");
QualType ResultTy;
if (BinaryOperator::isComparisonOp(Op))
ResultTy = SVB.getConditionType();
else if (BinaryOperator::isAdditiveOp(Op))
ResultTy = SymTy;
else
llvm_unreachable("Operation not suitable for unchecked rearrangement!");
if (LSym == RSym)
return SVB.evalBinOpNN(State, Op, nonloc::ConcreteInt(LInt),
nonloc::ConcreteInt(RInt), ResultTy)
.castAs<NonLoc>();
SymbolRef ResultSym = nullptr;
BinaryOperator::Opcode ResultOp;
llvm::APSInt ResultInt;
if (BinaryOperator::isComparisonOp(Op)) {
if (LInt > RInt) {
ResultSym = SymMgr.getSymSymExpr(RSym, BO_Sub, LSym, SymTy);
ResultOp = BinaryOperator::reverseComparisonOp(Op);
ResultInt = LInt - RInt; } else {
ResultSym = SymMgr.getSymSymExpr(LSym, BO_Sub, RSym, SymTy);
ResultOp = Op;
ResultInt = RInt - LInt; }
} else {
ResultSym = SymMgr.getSymSymExpr(LSym, Op, RSym, SymTy);
ResultInt = (Op == BO_Add) ? (LInt + RInt) : (LInt - RInt);
ResultOp = BO_Add;
if (ResultInt < 0) {
ResultInt = -ResultInt;
ResultOp = BO_Sub;
} else if (ResultInt == 0) {
return nonloc::SymbolVal(ResultSym);
}
}
const llvm::APSInt &PersistentResultInt = BV.getValue(ResultInt);
return nonloc::SymbolVal(
SymMgr.getSymIntExpr(ResultSym, ResultOp, PersistentResultInt, ResultTy));
}
static bool shouldRearrange(ProgramStateRef State, BinaryOperator::Opcode Op,
SymbolRef Sym, llvm::APSInt Int, QualType Ty) {
return Sym->getType() == Ty &&
(!BinaryOperator::isComparisonOp(Op) ||
(isWithinConstantOverflowBounds(Sym, State) &&
isWithinConstantOverflowBounds(Int)));
}
static Optional<NonLoc> tryRearrange(ProgramStateRef State,
BinaryOperator::Opcode Op, NonLoc Lhs,
NonLoc Rhs, QualType ResultTy) {
ProgramStateManager &StateMgr = State->getStateManager();
SValBuilder &SVB = StateMgr.getSValBuilder();
QualType SingleTy;
if (!SVB.getAnalyzerOptions().ShouldAggressivelySimplifyBinaryOperation)
return None;
SymbolRef LSym = Lhs.getAsSymbol();
if (!LSym)
return None;
if (BinaryOperator::isComparisonOp(Op)) {
SingleTy = LSym->getType();
if (ResultTy != SVB.getConditionType())
return None;
} else if (BinaryOperator::isAdditiveOp(Op)) {
SingleTy = ResultTy;
if (LSym->getType() != SingleTy)
return None;
} else {
return None;
}
assert(!SingleTy.isNull() && "We should have figured out the type by now!");
if (!SingleTy->isSignedIntegerOrEnumerationType())
return None;
SymbolRef RSym = Rhs.getAsSymbol();
if (!RSym || RSym->getType() != SingleTy)
return None;
BasicValueFactory &BV = State->getBasicVals();
llvm::APSInt LInt, RInt;
std::tie(LSym, LInt) = decomposeSymbol(LSym, BV);
std::tie(RSym, RInt) = decomposeSymbol(RSym, BV);
if (!shouldRearrange(State, Op, LSym, LInt, SingleTy) ||
!shouldRearrange(State, Op, RSym, RInt, SingleTy))
return None;
return doRearrangeUnchecked(State, Op, LSym, LInt, RSym, RInt);
}
SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
BinaryOperator::Opcode op,
NonLoc lhs, NonLoc rhs,
QualType resultTy) {
NonLoc InputLHS = lhs;
NonLoc InputRHS = rhs;
SVal simplifiedLhs = simplifySVal(state, lhs);
SVal simplifiedRhs = simplifySVal(state, rhs);
if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>())
lhs = *simplifiedLhsAsNonLoc;
if (auto simplifiedRhsAsNonLoc = simplifiedRhs.getAs<NonLoc>())
rhs = *simplifiedRhsAsNonLoc;
if (lhs == rhs)
switch (op) {
default:
break;
case BO_EQ:
case BO_LE:
case BO_GE:
return makeTruthVal(true, resultTy);
case BO_LT:
case BO_GT:
case BO_NE:
return makeTruthVal(false, resultTy);
case BO_Xor:
case BO_Sub:
if (resultTy->isIntegralOrEnumerationType())
return makeIntVal(0, resultTy);
return evalCast(makeIntVal(0, false), resultTy,
QualType{});
case BO_Or:
case BO_And:
return evalCast(lhs, resultTy, QualType{});
}
while (true) {
switch (lhs.getSubKind()) {
default:
return makeSymExprValNN(op, lhs, rhs, resultTy);
case nonloc::PointerToMemberKind: {
assert(rhs.getSubKind() == nonloc::PointerToMemberKind &&
"Both SVals should have pointer-to-member-type");
auto LPTM = lhs.castAs<nonloc::PointerToMember>(),
RPTM = rhs.castAs<nonloc::PointerToMember>();
auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData();
switch (op) {
case BO_EQ:
return makeTruthVal(LPTMD == RPTMD, resultTy);
case BO_NE:
return makeTruthVal(LPTMD != RPTMD, resultTy);
default:
return UnknownVal();
}
}
case nonloc::LocAsIntegerKind: {
Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc();
switch (rhs.getSubKind()) {
case nonloc::LocAsIntegerKind:
if (!BinaryOperator::isComparisonOp(op))
return UnknownVal();
return evalBinOpLL(state, op, lhsL,
rhs.castAs<nonloc::LocAsInteger>().getLoc(),
resultTy);
case nonloc::ConcreteIntKind: {
if (!BinaryOperator::isComparisonOp(op))
return UnknownVal();
llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue();
if (SymbolRef lSym = lhs.getAsLocSymbol(true))
BasicVals.getAPSIntType(lSym->getType()).apply(i);
else
BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
}
default:
switch (op) {
case BO_EQ:
return makeTruthVal(false, resultTy);
case BO_NE:
return makeTruthVal(true, resultTy);
default:
return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
}
}
}
case nonloc::ConcreteIntKind: {
llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
if (const llvm::APSInt *KnownRHSValue = getConstValue(state, rhs)) {
llvm::APSInt RHSValue = *KnownRHSValue;
if (BinaryOperator::isComparisonOp(op)) {
APSIntType CompareType = std::max(APSIntType(LHSValue),
APSIntType(RHSValue));
CompareType.apply(LHSValue);
CompareType.apply(RHSValue);
} else if (!BinaryOperator::isShiftOp(op)) {
APSIntType IntType = BasicVals.getAPSIntType(resultTy);
IntType.apply(LHSValue);
IntType.apply(RHSValue);
}
const llvm::APSInt *Result =
BasicVals.evalAPSInt(op, LHSValue, RHSValue);
if (!Result)
return UndefinedVal();
return nonloc::ConcreteInt(*Result);
}
switch (op) {
case BO_LT:
case BO_GT:
case BO_LE:
case BO_GE:
op = BinaryOperator::reverseComparisonOp(op);
LLVM_FALLTHROUGH;
case BO_EQ:
case BO_NE:
case BO_Add:
case BO_Mul:
case BO_And:
case BO_Xor:
case BO_Or:
std::swap(lhs, rhs);
continue;
case BO_Shr:
if (LHSValue.isAllOnes() && LHSValue.isSigned())
return evalCast(lhs, resultTy, QualType{});
LLVM_FALLTHROUGH;
case BO_Shl:
if (LHSValue == 0)
return evalCast(lhs, resultTy, QualType{});
return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
case BO_Div:
case BO_Rem:
if (LHSValue == 0)
return makeZeroVal(resultTy);
LLVM_FALLTHROUGH;
default:
return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
}
}
case nonloc::SymbolValKind: {
SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
if (op == BO_EQ && rhs.isZeroConstant()) {
BinaryOperator::Opcode opc = symIntExpr->getOpcode();
switch (opc) {
default:
break;
case BO_LAnd:
case BO_LOr:
llvm_unreachable("Logical operators handled by branching logic.");
case BO_Assign:
case BO_MulAssign:
case BO_DivAssign:
case BO_RemAssign:
case BO_AddAssign:
case BO_SubAssign:
case BO_ShlAssign:
case BO_ShrAssign:
case BO_AndAssign:
case BO_XorAssign:
case BO_OrAssign:
case BO_Comma:
llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
case BO_PtrMemD:
case BO_PtrMemI:
llvm_unreachable("Pointer arithmetic not handled here.");
case BO_LT:
case BO_GT:
case BO_LE:
case BO_GE:
case BO_EQ:
case BO_NE:
assert(resultTy->isBooleanType() ||
resultTy == getConditionType());
assert(symIntExpr->getType()->isBooleanType() ||
getContext().hasSameUnqualifiedType(symIntExpr->getType(),
getConditionType()));
opc = BinaryOperator::negateComparisonOp(opc);
return makeNonLoc(symIntExpr->getLHS(), opc,
symIntExpr->getRHS(), resultTy);
}
}
if (const llvm::APSInt *RHSValue = getConstValue(state, rhs)) {
if (BinaryOperator::isAdditiveOp(op)) {
BinaryOperator::Opcode lop = symIntExpr->getOpcode();
if (BinaryOperator::isAdditiveOp(lop)) {
APSIntType IntType = BasicVals.getAPSIntType(resultTy);
const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
const llvm::APSInt &second = IntType.convert(*RHSValue);
const llvm::APSInt *newRHS;
if (lop == op) {
newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
} else if (first >= second) {
newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
op = lop;
} else {
newRHS = BasicVals.evalAPSInt(BO_Sub, second, first);
}
assert(newRHS && "Invalid operation despite common type!");
rhs = nonloc::ConcreteInt(*newRHS);
lhs = nonloc::SymbolVal(symIntExpr->getLHS());
continue;
}
}
return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
}
}
if (const llvm::APSInt *RHSValue = getConstValue(state, rhs))
return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
if (Optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy))
return *V;
return makeSymExprValNN(op, InputLHS, InputRHS, resultTy);
}
}
}
}
static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR,
const FieldRegion *RightFR,
BinaryOperator::Opcode op,
QualType resultTy,
SimpleSValBuilder &SVB) {
if (!BinaryOperator::isComparisonOp(op))
return UnknownVal();
if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
return UnknownVal();
const FieldDecl *LeftFD = LeftFR->getDecl();
const FieldDecl *RightFD = RightFR->getDecl();
const RecordDecl *RD = LeftFD->getParent();
if (RD != RightFD->getParent())
return UnknownVal();
if (op == BO_EQ)
return SVB.makeTruthVal(false, resultTy);
if (op == BO_NE)
return SVB.makeTruthVal(true, resultTy);
bool leftFirst = (op == BO_LT || op == BO_LE);
for (const auto *I : RD->fields()) {
if (I == LeftFD)
return SVB.makeTruthVal(leftFirst, resultTy);
if (I == RightFD)
return SVB.makeTruthVal(!leftFirst, resultTy);
}
llvm_unreachable("Fields not found in parent record's definition");
}
static void assertEqualBitWidths(ProgramStateRef State, Loc RhsLoc,
Loc LhsLoc) {
ASTContext &Ctx = State->getStateManager().getContext();
uint64_t RhsBitwidth =
RhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(RhsLoc.getType(Ctx));
uint64_t LhsBitwidth =
LhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(LhsLoc.getType(Ctx));
if (RhsBitwidth && LhsBitwidth &&
(LhsLoc.getSubKind() == RhsLoc.getSubKind())) {
assert(RhsBitwidth == LhsBitwidth &&
"RhsLoc and LhsLoc bitwidth must be same!");
}
}
SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
BinaryOperator::Opcode op,
Loc lhs, Loc rhs,
QualType resultTy) {
assertEqualBitWidths(state, rhs, lhs);
if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
return UnknownVal();
if (lhs == rhs) {
switch (op) {
default:
llvm_unreachable("Unimplemented operation for two identical values");
case BO_Sub:
return makeZeroVal(resultTy);
case BO_EQ:
case BO_LE:
case BO_GE:
return makeTruthVal(true, resultTy);
case BO_NE:
case BO_LT:
case BO_GT:
return makeTruthVal(false, resultTy);
}
}
switch (lhs.getSubKind()) {
default:
llvm_unreachable("Ordering not implemented for this Loc.");
case loc::GotoLabelKind:
if (rhs.isZeroConstant()) {
switch (op) {
default:
break;
case BO_Sub:
return evalCast(lhs, resultTy, QualType{});
case BO_EQ:
case BO_LE:
case BO_LT:
return makeTruthVal(false, resultTy);
case BO_NE:
case BO_GT:
case BO_GE:
return makeTruthVal(true, resultTy);
}
}
return UnknownVal();
case loc::ConcreteIntKind: {
auto L = lhs.castAs<loc::ConcreteInt>();
if (SymbolRef rSym = rhs.getAsLocSymbol()) {
if (!BinaryOperator::isComparisonOp(op) || op == BO_Cmp)
return UnknownVal();
op = BinaryOperator::reverseComparisonOp(op);
return makeNonLoc(rSym, op, L.getValue(), resultTy);
}
if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
assert(BinaryOperator::isComparisonOp(op) || op == BO_Sub);
if (const auto *ResultInt =
BasicVals.evalAPSInt(op, L.getValue(), rInt->getValue()))
return evalCast(nonloc::ConcreteInt(*ResultInt), resultTy, QualType{});
return UnknownVal();
}
assert((isa<loc::MemRegionVal, loc::GotoLabel>(rhs)));
if (lhs.isZeroConstant()) {
switch (op) {
default:
break;
case BO_EQ:
case BO_GT:
case BO_GE:
return makeTruthVal(false, resultTy);
case BO_NE:
case BO_LT:
case BO_LE:
return makeTruthVal(true, resultTy);
}
}
return UnknownVal();
}
case loc::MemRegionValKind: {
if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
if (SymbolRef lSym = lhs.getAsLocSymbol(true)) {
if (BinaryOperator::isComparisonOp(op))
return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
return UnknownVal();
}
if (rInt->isZeroConstant()) {
if (op == BO_Sub)
return evalCast(lhs, resultTy, QualType{});
if (BinaryOperator::isComparisonOp(op)) {
QualType boolType = getContext().BoolTy;
NonLoc l = evalCast(lhs, boolType, QualType{}).castAs<NonLoc>();
NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>();
return evalBinOpNN(state, op, l, r, resultTy);
}
}
return UnknownVal();
}
const MemRegion *LeftMR = lhs.getAsRegion();
assert(LeftMR && "MemRegionValKind SVal doesn't have a region!");
const MemRegion *RightMR = rhs.getAsRegion();
if (!RightMR)
return UnknownVal();
const MemRegion *LeftBase = LeftMR->getBaseRegion();
const MemRegion *RightBase = RightMR->getBaseRegion();
const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
if (LeftMS != RightMS &&
((LeftMS != UnknownMS && RightMS != UnknownMS) ||
(isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
switch (op) {
default:
return UnknownVal();
case BO_EQ:
return makeTruthVal(false, resultTy);
case BO_NE:
return makeTruthVal(true, resultTy);
}
}
if (LeftBase != RightBase &&
((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
(isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
switch (op) {
default:
return UnknownVal();
case BO_EQ:
return makeTruthVal(false, resultTy);
case BO_NE:
return makeTruthVal(true, resultTy);
}
}
const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR);
if (RightER && LeftER) {
if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
LeftER->getElementType() == RightER->getElementType()) {
SVal LeftIndexVal = LeftER->getIndex();
Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
if (!LeftIndex)
return UnknownVal();
LeftIndexVal = evalCast(*LeftIndex, ArrayIndexTy, QualType{});
LeftIndex = LeftIndexVal.getAs<NonLoc>();
if (!LeftIndex)
return UnknownVal();
SVal RightIndexVal = RightER->getIndex();
Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
if (!RightIndex)
return UnknownVal();
RightIndexVal = evalCast(*RightIndex, ArrayIndexTy, QualType{});
RightIndex = RightIndexVal.getAs<NonLoc>();
if (!RightIndex)
return UnknownVal();
return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
}
}
const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR);
if (RightFR && LeftFR) {
SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy,
*this);
if (!R.isUnknown())
return R;
}
RegionOffset LeftOffset = LeftMR->getAsOffset();
RegionOffset RightOffset = RightMR->getAsOffset();
if (LeftOffset.getRegion() != nullptr &&
LeftOffset.getRegion() == RightOffset.getRegion() &&
!LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) {
int64_t left = LeftOffset.getOffset();
int64_t right = RightOffset.getOffset();
switch (op) {
default:
return UnknownVal();
case BO_LT:
return makeTruthVal(left < right, resultTy);
case BO_GT:
return makeTruthVal(left > right, resultTy);
case BO_LE:
return makeTruthVal(left <= right, resultTy);
case BO_GE:
return makeTruthVal(left >= right, resultTy);
case BO_EQ:
return makeTruthVal(left == right, resultTy);
case BO_NE:
return makeTruthVal(left != right, resultTy);
}
}
SymbolRef LHSSym = lhs.getAsLocSymbol();
SymbolRef RHSSym = rhs.getAsLocSymbol();
if (LHSSym && RHSSym)
return makeNonLoc(LHSSym, op, RHSSym, resultTy);
return UnknownVal();
}
}
}
SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
BinaryOperator::Opcode op, Loc lhs,
NonLoc rhs, QualType resultTy) {
if (op >= BO_PtrMemD && op <= BO_PtrMemI) {
if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) {
if (PTMSV->isNullMemberPointer())
return UndefinedVal();
auto getFieldLValue = [&](const auto *FD) -> SVal {
SVal Result = lhs;
for (const auto &I : *PTMSV)
Result = StateMgr.getStoreManager().evalDerivedToBase(
Result, I->getType(), I->isVirtual());
return state->getLValue(FD, Result);
};
if (const auto *FD = PTMSV->getDeclAs<FieldDecl>()) {
return getFieldLValue(FD);
}
if (const auto *FD = PTMSV->getDeclAs<IndirectFieldDecl>()) {
return getFieldLValue(FD);
}
}
return rhs;
}
assert(!BinaryOperator::isComparisonOp(op) &&
"arguments to comparison ops must be of the same type");
if (rhs.isZeroConstant())
return lhs;
if (lhs.isZeroConstant())
return lhs;
if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) {
if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) {
const llvm::APSInt &leftI = lhsInt->getValue();
assert(leftI.isUnsigned());
llvm::APSInt rightI(rhsInt->getValue(), true);
rightI = rightI.extOrTrunc(leftI.getBitWidth());
llvm::APSInt Multiplicand(rightI.getBitWidth(), true);
QualType pointeeType = resultTy->getPointeeType();
Multiplicand = getContext().getTypeSizeInChars(pointeeType).getQuantity();
rightI *= Multiplicand;
switch (op) {
case BO_Add:
rightI = leftI + rightI;
break;
case BO_Sub:
rightI = leftI - rightI;
break;
default:
llvm_unreachable("Invalid pointer arithmetic operation");
}
return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
}
}
if (const MemRegion *region = lhs.getAsRegion()) {
rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
SVal index = UnknownVal();
const SubRegion *superR = nullptr;
QualType elementType;
if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
assert(op == BO_Add || op == BO_Sub);
index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
getArrayIndexType());
superR = cast<SubRegion>(elemReg->getSuperRegion());
elementType = elemReg->getElementType();
}
else if (isa<SubRegion>(region)) {
assert(op == BO_Add || op == BO_Sub);
index = (op == BO_Add) ? rhs : evalMinus(rhs);
superR = cast<SubRegion>(region);
if (resultTy->isAnyPointerType())
elementType = resultTy->getPointeeType();
}
if (elementType->isVoidType())
elementType = getContext().CharTy;
if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) {
return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
superR, getContext()));
}
}
return UnknownVal();
}
const llvm::APSInt *SimpleSValBuilder::getConstValue(ProgramStateRef state,
SVal V) {
if (V.isUnknownOrUndef())
return nullptr;
if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
return &X->getValue();
if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
return &X->getValue();
if (SymbolRef Sym = V.getAsSymbol())
return state->getConstraintManager().getSymVal(state, Sym);
return nullptr;
}
const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
SVal V) {
return getConstValue(state, simplifySVal(state, V));
}
SVal SimpleSValBuilder::simplifyUntilFixpoint(ProgramStateRef State, SVal Val) {
SVal SimplifiedVal = simplifySValOnce(State, Val);
while (SimplifiedVal != Val) {
Val = SimplifiedVal;
SimplifiedVal = simplifySValOnce(State, Val);
}
return SimplifiedVal;
}
SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) {
return simplifyUntilFixpoint(State, V);
}
SVal SimpleSValBuilder::simplifySValOnce(ProgramStateRef State, SVal V) {
class Simplifier : public FullSValVisitor<Simplifier, SVal> {
ProgramStateRef State;
SValBuilder &SVB;
llvm::DenseMap<SymbolRef, SVal> Cached;
static bool isUnchanged(SymbolRef Sym, SVal Val) {
return Sym == Val.getAsSymbol();
}
SVal cache(SymbolRef Sym, SVal V) {
Cached[Sym] = V;
return V;
}
SVal skip(SymbolRef Sym) {
return cache(Sym, SVB.makeSymbolVal(Sym));
}
SVal getConst(SymbolRef Sym) {
const llvm::APSInt *Const =
State->getConstraintManager().getSymVal(State, Sym);
if (Const)
return Loc::isLocType(Sym->getType()) ? (SVal)SVB.makeIntLocVal(*Const)
: (SVal)SVB.makeIntVal(*Const);
return UndefinedVal();
}
SVal getConstOrVisit(SymbolRef Sym) {
const SVal Ret = getConst(Sym);
if (Ret.isUndef())
return Visit(Sym);
return Ret;
}
public:
Simplifier(ProgramStateRef State)
: State(State), SVB(State->getStateManager().getSValBuilder()) {}
SVal VisitSymbolData(const SymbolData *S) {
if (const llvm::APSInt *I =
State->getConstraintManager().getSymVal(State, S))
return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I)
: (SVal)SVB.makeIntVal(*I);
return SVB.makeSymbolVal(S);
}
SVal VisitSymIntExpr(const SymIntExpr *S) {
auto I = Cached.find(S);
if (I != Cached.end())
return I->second;
SVal LHS = getConstOrVisit(S->getLHS());
if (isUnchanged(S->getLHS(), LHS))
return skip(S);
SVal RHS;
if (Loc::isLocType(S->getLHS()->getType()) &&
BinaryOperator::isComparisonOp(S->getOpcode())) {
if (SymbolRef Sym = LHS.getAsSymbol()) {
assert(Loc::isLocType(Sym->getType()));
LHS = SVB.makeLoc(Sym);
}
RHS = SVB.makeIntLocVal(S->getRHS());
} else {
RHS = SVB.makeIntVal(S->getRHS());
}
return cache(
S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
}
SVal VisitIntSymExpr(const IntSymExpr *S) {
auto I = Cached.find(S);
if (I != Cached.end())
return I->second;
SVal RHS = getConstOrVisit(S->getRHS());
if (isUnchanged(S->getRHS(), RHS))
return skip(S);
SVal LHS = SVB.makeIntVal(S->getLHS());
return cache(
S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
}
SVal VisitSymSymExpr(const SymSymExpr *S) {
auto I = Cached.find(S);
if (I != Cached.end())
return I->second;
if (Loc::isLocType(S->getLHS()->getType()) !=
Loc::isLocType(S->getRHS()->getType()))
return skip(S);
SVal LHS = getConstOrVisit(S->getLHS());
SVal RHS = getConstOrVisit(S->getRHS());
if (isUnchanged(S->getLHS(), LHS) && isUnchanged(S->getRHS(), RHS))
return skip(S);
return cache(
S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType()));
}
SVal VisitSymbolCast(const SymbolCast *S) {
auto I = Cached.find(S);
if (I != Cached.end())
return I->second;
const SymExpr *OpSym = S->getOperand();
SVal OpVal = getConstOrVisit(OpSym);
if (isUnchanged(OpSym, OpVal))
return skip(S);
return cache(S, SVB.evalCast(OpVal, S->getType(), OpSym->getType()));
}
SVal VisitUnarySymExpr(const UnarySymExpr *S) {
auto I = Cached.find(S);
if (I != Cached.end())
return I->second;
SVal Op = getConstOrVisit(S->getOperand());
if (isUnchanged(S->getOperand(), Op))
return skip(S);
return cache(
S, SVB.evalUnaryOp(State, S->getOpcode(), Op, S->getType()));
}
SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); }
SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); }
SVal VisitNonLocSymbolVal(nonloc::SymbolVal V) {
return Visit(V.getSymbol());
}
SVal VisitSVal(SVal V) { return V; }
};
SVal SimplifiedV = Simplifier(State).Visit(V);
return SimplifiedV;
}