1fa0734ecSArgyrios Kyrtzidis // SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- C++ -*- 2fa0734ecSArgyrios Kyrtzidis // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6fa0734ecSArgyrios Kyrtzidis // 7fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===// 8fa0734ecSArgyrios Kyrtzidis // 9fa0734ecSArgyrios Kyrtzidis // This file defines SimpleSValBuilder, a basic implementation of SValBuilder. 10fa0734ecSArgyrios Kyrtzidis // 11fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===// 12fa0734ecSArgyrios Kyrtzidis 13f8cbac4bSTed Kremenek #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h" 143a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h" 15d70ec366SAdam Balogh #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 16001fd5b4STed Kremenek #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 1712294f8dSArtem Dergachev #include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h" 18fa0734ecSArgyrios Kyrtzidis 19fa0734ecSArgyrios Kyrtzidis using namespace clang; 20fa0734ecSArgyrios Kyrtzidis using namespace ento; 21fa0734ecSArgyrios Kyrtzidis 22fa0734ecSArgyrios Kyrtzidis namespace { 23fa0734ecSArgyrios Kyrtzidis class SimpleSValBuilder : public SValBuilder { 24978431e8SGabor Marton 25*bc2c759aSGabor Marton // Query the constraint manager whether the SVal has only one possible 26*bc2c759aSGabor Marton // (integer) value. If that is the case, the value is returned. Otherwise, 27*bc2c759aSGabor Marton // returns NULL. 28*bc2c759aSGabor Marton // This is an implementation detail. Checkers should use `getKnownValue()` 29*bc2c759aSGabor Marton // instead. 30*bc2c759aSGabor Marton const llvm::APSInt *getConstValue(ProgramStateRef state, SVal V); 31*bc2c759aSGabor Marton 32978431e8SGabor Marton // With one `simplifySValOnce` call, a compound symbols might collapse to 33978431e8SGabor Marton // simpler symbol tree that is still possible to further simplify. Thus, we 34978431e8SGabor Marton // do the simplification on a new symbol tree until we reach the simplest 35978431e8SGabor Marton // form, i.e. the fixpoint. 36978431e8SGabor Marton // Consider the following symbol `(b * b) * b * b` which has this tree: 37978431e8SGabor Marton // * 38978431e8SGabor Marton // / \ 39978431e8SGabor Marton // * b 40978431e8SGabor Marton // / \ 41978431e8SGabor Marton // / b 42978431e8SGabor Marton // (b * b) 43978431e8SGabor Marton // Now, if the `b * b == 1` new constraint is added then during the first 44978431e8SGabor Marton // iteration we have the following transformations: 45978431e8SGabor Marton // * * 46978431e8SGabor Marton // / \ / \ 47978431e8SGabor Marton // * b --> b b 48978431e8SGabor Marton // / \ 49978431e8SGabor Marton // / b 50978431e8SGabor Marton // 1 51978431e8SGabor Marton // We need another iteration to reach the final result `1`. 52978431e8SGabor Marton SVal simplifyUntilFixpoint(ProgramStateRef State, SVal Val); 53978431e8SGabor Marton 54978431e8SGabor Marton // Recursively descends into symbolic expressions and replaces symbols 55*bc2c759aSGabor Marton // with their known values (in the sense of the getConstValue() method). 56978431e8SGabor Marton // We traverse the symbol tree and query the constraint values for the 57978431e8SGabor Marton // sub-trees and if a value is a constant we do the constant folding. 58978431e8SGabor Marton SVal simplifySValOnce(ProgramStateRef State, SVal V); 59978431e8SGabor Marton 60fa0734ecSArgyrios Kyrtzidis public: 61fa0734ecSArgyrios Kyrtzidis SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context, 62001fd5b4STed Kremenek ProgramStateManager &stateMgr) 63fa0734ecSArgyrios Kyrtzidis : SValBuilder(alloc, context, stateMgr) {} 64637d1e66SAngel Garcia Gomez ~SimpleSValBuilder() override {} 65fa0734ecSArgyrios Kyrtzidis 66fb6b25b5SCraig Topper SVal evalMinus(NonLoc val) override; 67fb6b25b5SCraig Topper SVal evalComplement(NonLoc val) override; 68fb6b25b5SCraig Topper SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op, 69fb6b25b5SCraig Topper NonLoc lhs, NonLoc rhs, QualType resultTy) override; 70fb6b25b5SCraig Topper SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op, 71fb6b25b5SCraig Topper Loc lhs, Loc rhs, QualType resultTy) override; 72fb6b25b5SCraig Topper SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op, 73fb6b25b5SCraig Topper Loc lhs, NonLoc rhs, QualType resultTy) override; 74fa0734ecSArgyrios Kyrtzidis 75*bc2c759aSGabor Marton /// Evaluates a given SVal by recursively evaluating and 76*bc2c759aSGabor Marton /// simplifying the children SVals. If the SVal has only one possible 77fa0734ecSArgyrios Kyrtzidis /// (integer) value, that value is returned. Otherwise, returns NULL. 78fb6b25b5SCraig Topper const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override; 79fa0734ecSArgyrios Kyrtzidis 8012294f8dSArtem Dergachev SVal simplifySVal(ProgramStateRef State, SVal V) override; 8112294f8dSArtem Dergachev 82fa0734ecSArgyrios Kyrtzidis SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op, 83fa0734ecSArgyrios Kyrtzidis const llvm::APSInt &RHS, QualType resultTy); 84fa0734ecSArgyrios Kyrtzidis }; 85fa0734ecSArgyrios Kyrtzidis } // end anonymous namespace 86fa0734ecSArgyrios Kyrtzidis 87fa0734ecSArgyrios Kyrtzidis SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc, 88fa0734ecSArgyrios Kyrtzidis ASTContext &context, 89001fd5b4STed Kremenek ProgramStateManager &stateMgr) { 90fa0734ecSArgyrios Kyrtzidis return new SimpleSValBuilder(alloc, context, stateMgr); 91fa0734ecSArgyrios Kyrtzidis } 92fa0734ecSArgyrios Kyrtzidis 93fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===// 94fa0734ecSArgyrios Kyrtzidis // Transfer function for unary operators. 95fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===// 96fa0734ecSArgyrios Kyrtzidis 97fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::evalMinus(NonLoc val) { 98fa0734ecSArgyrios Kyrtzidis switch (val.getSubKind()) { 99fa0734ecSArgyrios Kyrtzidis case nonloc::ConcreteIntKind: 1002fdacbc5SDavid Blaikie return val.castAs<nonloc::ConcreteInt>().evalMinus(*this); 101b5b2aec1SGabor Marton case nonloc::SymbolValKind: 102b5b2aec1SGabor Marton return makeNonLoc(val.castAs<nonloc::SymbolVal>().getSymbol(), UO_Minus, 103b5b2aec1SGabor Marton val.getType(Context)); 104fa0734ecSArgyrios Kyrtzidis default: 105fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 106fa0734ecSArgyrios Kyrtzidis } 107fa0734ecSArgyrios Kyrtzidis } 108fa0734ecSArgyrios Kyrtzidis 109fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::evalComplement(NonLoc X) { 110fa0734ecSArgyrios Kyrtzidis switch (X.getSubKind()) { 111fa0734ecSArgyrios Kyrtzidis case nonloc::ConcreteIntKind: 1122fdacbc5SDavid Blaikie return X.castAs<nonloc::ConcreteInt>().evalComplement(*this); 113b5b2aec1SGabor Marton case nonloc::SymbolValKind: 114b5b2aec1SGabor Marton return makeNonLoc(X.castAs<nonloc::SymbolVal>().getSymbol(), UO_Not, 115b5b2aec1SGabor Marton X.getType(Context)); 116fa0734ecSArgyrios Kyrtzidis default: 117fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 118fa0734ecSArgyrios Kyrtzidis } 119fa0734ecSArgyrios Kyrtzidis } 120fa0734ecSArgyrios Kyrtzidis 12114742443STomasz Kamiński // Checks if the negation the value and flipping sign preserve 12214742443STomasz Kamiński // the semantics on the operation in the resultType 12314742443STomasz Kamiński static bool isNegationValuePreserving(const llvm::APSInt &Value, 12414742443STomasz Kamiński APSIntType ResultType) { 12514742443STomasz Kamiński const unsigned ValueBits = Value.getSignificantBits(); 12614742443STomasz Kamiński if (ValueBits == ResultType.getBitWidth()) { 12714742443STomasz Kamiński // The value is the lowest negative value that is representable 12814742443STomasz Kamiński // in signed integer with bitWith of result type. The 12914742443STomasz Kamiński // negation is representable if resultType is unsigned. 13014742443STomasz Kamiński return ResultType.isUnsigned(); 13114742443STomasz Kamiński } 13214742443STomasz Kamiński 13314742443STomasz Kamiński // If resultType bitWith is higher that number of bits required 13414742443STomasz Kamiński // to represent RHS, the sign flip produce same value. 13514742443STomasz Kamiński return ValueBits < ResultType.getBitWidth(); 13614742443STomasz Kamiński } 13714742443STomasz Kamiński 138fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===// 139fa0734ecSArgyrios Kyrtzidis // Transfer function for binary operators. 140fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===// 141fa0734ecSArgyrios Kyrtzidis 142fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS, 143fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode op, 144fa0734ecSArgyrios Kyrtzidis const llvm::APSInt &RHS, 145fa0734ecSArgyrios Kyrtzidis QualType resultTy) { 146fa0734ecSArgyrios Kyrtzidis bool isIdempotent = false; 147fa0734ecSArgyrios Kyrtzidis 148fa0734ecSArgyrios Kyrtzidis // Check for a few special cases with known reductions first. 149fa0734ecSArgyrios Kyrtzidis switch (op) { 150fa0734ecSArgyrios Kyrtzidis default: 151fa0734ecSArgyrios Kyrtzidis // We can't reduce this case; just treat it normally. 152fa0734ecSArgyrios Kyrtzidis break; 153fa0734ecSArgyrios Kyrtzidis case BO_Mul: 154fa0734ecSArgyrios Kyrtzidis // a*0 and a*1 155fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 156fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy); 157fa0734ecSArgyrios Kyrtzidis else if (RHS == 1) 158fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 159fa0734ecSArgyrios Kyrtzidis break; 160fa0734ecSArgyrios Kyrtzidis case BO_Div: 161fa0734ecSArgyrios Kyrtzidis // a/0 and a/1 162fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 163fa0734ecSArgyrios Kyrtzidis // This is also handled elsewhere. 164fa0734ecSArgyrios Kyrtzidis return UndefinedVal(); 165fa0734ecSArgyrios Kyrtzidis else if (RHS == 1) 166fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 167fa0734ecSArgyrios Kyrtzidis break; 168fa0734ecSArgyrios Kyrtzidis case BO_Rem: 169fa0734ecSArgyrios Kyrtzidis // a%0 and a%1 170fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 171fa0734ecSArgyrios Kyrtzidis // This is also handled elsewhere. 172fa0734ecSArgyrios Kyrtzidis return UndefinedVal(); 173fa0734ecSArgyrios Kyrtzidis else if (RHS == 1) 174fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy); 175fa0734ecSArgyrios Kyrtzidis break; 176fa0734ecSArgyrios Kyrtzidis case BO_Add: 177fa0734ecSArgyrios Kyrtzidis case BO_Sub: 178fa0734ecSArgyrios Kyrtzidis case BO_Shl: 179fa0734ecSArgyrios Kyrtzidis case BO_Shr: 180fa0734ecSArgyrios Kyrtzidis case BO_Xor: 181fa0734ecSArgyrios Kyrtzidis // a+0, a-0, a<<0, a>>0, a^0 182fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 183fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 184fa0734ecSArgyrios Kyrtzidis break; 185fa0734ecSArgyrios Kyrtzidis case BO_And: 186fa0734ecSArgyrios Kyrtzidis // a&0 and a&(~0) 187fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 188fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy); 189d933adeaSJay Foad else if (RHS.isAllOnes()) 190fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 191fa0734ecSArgyrios Kyrtzidis break; 192fa0734ecSArgyrios Kyrtzidis case BO_Or: 193fa0734ecSArgyrios Kyrtzidis // a|0 and a|(~0) 194fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 195fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 196d933adeaSJay Foad else if (RHS.isAllOnes()) { 197fa0734ecSArgyrios Kyrtzidis const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS); 198fa0734ecSArgyrios Kyrtzidis return nonloc::ConcreteInt(Result); 199fa0734ecSArgyrios Kyrtzidis } 200fa0734ecSArgyrios Kyrtzidis break; 201fa0734ecSArgyrios Kyrtzidis } 202fa0734ecSArgyrios Kyrtzidis 203fa0734ecSArgyrios Kyrtzidis // Idempotent ops (like a*1) can still change the type of an expression. 20401ddfa95SDenys Petrov // Wrap the LHS up in a NonLoc again and let evalCast do the 2055ad574c0SZhanyong Wan // dirty work. 206d066f79cSAnna Zaks if (isIdempotent) 20701ddfa95SDenys Petrov return evalCast(nonloc::SymbolVal(LHS), resultTy, QualType{}); 208fa0734ecSArgyrios Kyrtzidis 209fa0734ecSArgyrios Kyrtzidis // If we reach this point, the expression cannot be simplified. 21054569448SJordy Rose // Make a SymbolVal for the entire expression, after converting the RHS. 21154569448SJordy Rose const llvm::APSInt *ConvertedRHS = &RHS; 21254569448SJordy Rose if (BinaryOperator::isComparisonOp(op)) { 21354569448SJordy Rose // We're looking for a type big enough to compare the symbolic value 21454569448SJordy Rose // with the given constant. 21554569448SJordy Rose // FIXME: This is an approximation of Sema::UsualArithmeticConversions. 21654569448SJordy Rose ASTContext &Ctx = getContext(); 217a808e165STed Kremenek QualType SymbolType = LHS->getType(); 21854569448SJordy Rose uint64_t ValWidth = RHS.getBitWidth(); 21954569448SJordy Rose uint64_t TypeWidth = Ctx.getTypeSize(SymbolType); 22054569448SJordy Rose 22154569448SJordy Rose if (ValWidth < TypeWidth) { 22254569448SJordy Rose // If the value is too small, extend it. 22354569448SJordy Rose ConvertedRHS = &BasicVals.Convert(SymbolType, RHS); 22454569448SJordy Rose } else if (ValWidth == TypeWidth) { 22554569448SJordy Rose // If the value is signed but the symbol is unsigned, do the comparison 22654569448SJordy Rose // in unsigned space. [C99 6.3.1.8] 22754569448SJordy Rose // (For the opposite case, the value is already unsigned.) 22854569448SJordy Rose if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType()) 22954569448SJordy Rose ConvertedRHS = &BasicVals.Convert(SymbolType, RHS); 23054569448SJordy Rose } 23114742443STomasz Kamiński } else if (BinaryOperator::isAdditiveOp(op) && RHS.isNegative()) { 23214742443STomasz Kamiński // Change a+(-N) into a-N, and a-(-N) into a+N 23314742443STomasz Kamiński // Adjust addition/subtraction of negative value, to 23414742443STomasz Kamiński // subtraction/addition of the negated value. 23514742443STomasz Kamiński APSIntType resultIntTy = BasicVals.getAPSIntType(resultTy); 23614742443STomasz Kamiński if (isNegationValuePreserving(RHS, resultIntTy)) { 23714742443STomasz Kamiński ConvertedRHS = &BasicVals.getValue(-resultIntTy.convert(RHS)); 23814742443STomasz Kamiński op = (op == BO_Add) ? BO_Sub : BO_Add; 23914742443STomasz Kamiński } else { 24014742443STomasz Kamiński ConvertedRHS = &BasicVals.Convert(resultTy, RHS); 24114742443STomasz Kamiński } 242da5b5ae8SBalazs Benics } else 24354569448SJordy Rose ConvertedRHS = &BasicVals.Convert(resultTy, RHS); 24454569448SJordy Rose 24554569448SJordy Rose return makeNonLoc(LHS, op, *ConvertedRHS, resultTy); 246fa0734ecSArgyrios Kyrtzidis } 247fa0734ecSArgyrios Kyrtzidis 2482bbccca9SAdam Balogh // See if Sym is known to be a relation Rel with Bound. 2492bbccca9SAdam Balogh static bool isInRelation(BinaryOperator::Opcode Rel, SymbolRef Sym, 2502bbccca9SAdam Balogh llvm::APSInt Bound, ProgramStateRef State) { 2512bbccca9SAdam Balogh SValBuilder &SVB = State->getStateManager().getSValBuilder(); 2522bbccca9SAdam Balogh SVal Result = 2532bbccca9SAdam Balogh SVB.evalBinOpNN(State, Rel, nonloc::SymbolVal(Sym), 2542bbccca9SAdam Balogh nonloc::ConcreteInt(Bound), SVB.getConditionType()); 2552bbccca9SAdam Balogh if (auto DV = Result.getAs<DefinedSVal>()) { 2562bbccca9SAdam Balogh return !State->assume(*DV, false); 2572bbccca9SAdam Balogh } 2582bbccca9SAdam Balogh return false; 2592bbccca9SAdam Balogh } 2602bbccca9SAdam Balogh 2612bbccca9SAdam Balogh // See if Sym is known to be within [min/4, max/4], where min and max 2622bbccca9SAdam Balogh // are the bounds of the symbol's integral type. With such symbols, 2632bbccca9SAdam Balogh // some manipulations can be performed without the risk of overflow. 2642bbccca9SAdam Balogh // assume() doesn't cause infinite recursion because we should be dealing 2652bbccca9SAdam Balogh // with simpler symbols on every recursive call. 2662bbccca9SAdam Balogh static bool isWithinConstantOverflowBounds(SymbolRef Sym, 2672bbccca9SAdam Balogh ProgramStateRef State) { 2682bbccca9SAdam Balogh SValBuilder &SVB = State->getStateManager().getSValBuilder(); 2692bbccca9SAdam Balogh BasicValueFactory &BV = SVB.getBasicValueFactory(); 2702bbccca9SAdam Balogh 2712bbccca9SAdam Balogh QualType T = Sym->getType(); 2722bbccca9SAdam Balogh assert(T->isSignedIntegerOrEnumerationType() && 2732bbccca9SAdam Balogh "This only works with signed integers!"); 2742bbccca9SAdam Balogh APSIntType AT = BV.getAPSIntType(T); 2752bbccca9SAdam Balogh 2762bbccca9SAdam Balogh llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max; 2772bbccca9SAdam Balogh return isInRelation(BO_LE, Sym, Max, State) && 2782bbccca9SAdam Balogh isInRelation(BO_GE, Sym, Min, State); 2792bbccca9SAdam Balogh } 2802bbccca9SAdam Balogh 2812bbccca9SAdam Balogh // Same for the concrete integers: see if I is within [min/4, max/4]. 2822bbccca9SAdam Balogh static bool isWithinConstantOverflowBounds(llvm::APSInt I) { 2832bbccca9SAdam Balogh APSIntType AT(I); 2842bbccca9SAdam Balogh assert(!AT.isUnsigned() && 2852bbccca9SAdam Balogh "This only works with signed integers!"); 2862bbccca9SAdam Balogh 2872bbccca9SAdam Balogh llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max; 2882bbccca9SAdam Balogh return (I <= Max) && (I >= -Max); 2892bbccca9SAdam Balogh } 2902bbccca9SAdam Balogh 2912bbccca9SAdam Balogh static std::pair<SymbolRef, llvm::APSInt> 2922bbccca9SAdam Balogh decomposeSymbol(SymbolRef Sym, BasicValueFactory &BV) { 2932bbccca9SAdam Balogh if (const auto *SymInt = dyn_cast<SymIntExpr>(Sym)) 2942bbccca9SAdam Balogh if (BinaryOperator::isAdditiveOp(SymInt->getOpcode())) 2952bbccca9SAdam Balogh return std::make_pair(SymInt->getLHS(), 2962bbccca9SAdam Balogh (SymInt->getOpcode() == BO_Add) ? 2972bbccca9SAdam Balogh (SymInt->getRHS()) : 2982bbccca9SAdam Balogh (-SymInt->getRHS())); 2992bbccca9SAdam Balogh 3002bbccca9SAdam Balogh // Fail to decompose: "reduce" the problem to the "$x + 0" case. 3012bbccca9SAdam Balogh return std::make_pair(Sym, BV.getValue(0, Sym->getType())); 3022bbccca9SAdam Balogh } 3032bbccca9SAdam Balogh 3042bbccca9SAdam Balogh // Simplify "(LSym + LInt) Op (RSym + RInt)" assuming all values are of the 3052bbccca9SAdam Balogh // same signed integral type and no overflows occur (which should be checked 3062bbccca9SAdam Balogh // by the caller). 3072bbccca9SAdam Balogh static NonLoc doRearrangeUnchecked(ProgramStateRef State, 3082bbccca9SAdam Balogh BinaryOperator::Opcode Op, 3092bbccca9SAdam Balogh SymbolRef LSym, llvm::APSInt LInt, 3102bbccca9SAdam Balogh SymbolRef RSym, llvm::APSInt RInt) { 3112bbccca9SAdam Balogh SValBuilder &SVB = State->getStateManager().getSValBuilder(); 3122bbccca9SAdam Balogh BasicValueFactory &BV = SVB.getBasicValueFactory(); 3132bbccca9SAdam Balogh SymbolManager &SymMgr = SVB.getSymbolManager(); 3142bbccca9SAdam Balogh 3152bbccca9SAdam Balogh QualType SymTy = LSym->getType(); 3162bbccca9SAdam Balogh assert(SymTy == RSym->getType() && 3172bbccca9SAdam Balogh "Symbols are not of the same type!"); 3182bbccca9SAdam Balogh assert(APSIntType(LInt) == BV.getAPSIntType(SymTy) && 3192bbccca9SAdam Balogh "Integers are not of the same type as symbols!"); 3202bbccca9SAdam Balogh assert(APSIntType(RInt) == BV.getAPSIntType(SymTy) && 3212bbccca9SAdam Balogh "Integers are not of the same type as symbols!"); 3222bbccca9SAdam Balogh 3232bbccca9SAdam Balogh QualType ResultTy; 3242bbccca9SAdam Balogh if (BinaryOperator::isComparisonOp(Op)) 3252bbccca9SAdam Balogh ResultTy = SVB.getConditionType(); 3262bbccca9SAdam Balogh else if (BinaryOperator::isAdditiveOp(Op)) 3272bbccca9SAdam Balogh ResultTy = SymTy; 3282bbccca9SAdam Balogh else 3292bbccca9SAdam Balogh llvm_unreachable("Operation not suitable for unchecked rearrangement!"); 3302bbccca9SAdam Balogh 3312bbccca9SAdam Balogh if (LSym == RSym) 3322bbccca9SAdam Balogh return SVB.evalBinOpNN(State, Op, nonloc::ConcreteInt(LInt), 3332bbccca9SAdam Balogh nonloc::ConcreteInt(RInt), ResultTy) 3342bbccca9SAdam Balogh .castAs<NonLoc>(); 3352bbccca9SAdam Balogh 3362bbccca9SAdam Balogh SymbolRef ResultSym = nullptr; 3372bbccca9SAdam Balogh BinaryOperator::Opcode ResultOp; 3382bbccca9SAdam Balogh llvm::APSInt ResultInt; 3392bbccca9SAdam Balogh if (BinaryOperator::isComparisonOp(Op)) { 3402bbccca9SAdam Balogh // Prefer comparing to a non-negative number. 3412bbccca9SAdam Balogh // FIXME: Maybe it'd be better to have consistency in 3422bbccca9SAdam Balogh // "$x - $y" vs. "$y - $x" because those are solver's keys. 3432bbccca9SAdam Balogh if (LInt > RInt) { 3442bbccca9SAdam Balogh ResultSym = SymMgr.getSymSymExpr(RSym, BO_Sub, LSym, SymTy); 3452bbccca9SAdam Balogh ResultOp = BinaryOperator::reverseComparisonOp(Op); 3462bbccca9SAdam Balogh ResultInt = LInt - RInt; // Opposite order! 3472bbccca9SAdam Balogh } else { 3482bbccca9SAdam Balogh ResultSym = SymMgr.getSymSymExpr(LSym, BO_Sub, RSym, SymTy); 3492bbccca9SAdam Balogh ResultOp = Op; 3502bbccca9SAdam Balogh ResultInt = RInt - LInt; // Opposite order! 3512bbccca9SAdam Balogh } 3522bbccca9SAdam Balogh } else { 3532bbccca9SAdam Balogh ResultSym = SymMgr.getSymSymExpr(LSym, Op, RSym, SymTy); 3542bbccca9SAdam Balogh ResultInt = (Op == BO_Add) ? (LInt + RInt) : (LInt - RInt); 3552bbccca9SAdam Balogh ResultOp = BO_Add; 3562bbccca9SAdam Balogh // Bring back the cosmetic difference. 3572bbccca9SAdam Balogh if (ResultInt < 0) { 3582bbccca9SAdam Balogh ResultInt = -ResultInt; 3592bbccca9SAdam Balogh ResultOp = BO_Sub; 3602bbccca9SAdam Balogh } else if (ResultInt == 0) { 3612bbccca9SAdam Balogh // Shortcut: Simplify "$x + 0" to "$x". 3622bbccca9SAdam Balogh return nonloc::SymbolVal(ResultSym); 3632bbccca9SAdam Balogh } 3642bbccca9SAdam Balogh } 3652bbccca9SAdam Balogh const llvm::APSInt &PersistentResultInt = BV.getValue(ResultInt); 3662bbccca9SAdam Balogh return nonloc::SymbolVal( 3672bbccca9SAdam Balogh SymMgr.getSymIntExpr(ResultSym, ResultOp, PersistentResultInt, ResultTy)); 3682bbccca9SAdam Balogh } 3692bbccca9SAdam Balogh 3702bbccca9SAdam Balogh // Rearrange if symbol type matches the result type and if the operator is a 3712bbccca9SAdam Balogh // comparison operator, both symbol and constant must be within constant 3722bbccca9SAdam Balogh // overflow bounds. 3732bbccca9SAdam Balogh static bool shouldRearrange(ProgramStateRef State, BinaryOperator::Opcode Op, 3742bbccca9SAdam Balogh SymbolRef Sym, llvm::APSInt Int, QualType Ty) { 3752bbccca9SAdam Balogh return Sym->getType() == Ty && 3762bbccca9SAdam Balogh (!BinaryOperator::isComparisonOp(Op) || 3772bbccca9SAdam Balogh (isWithinConstantOverflowBounds(Sym, State) && 3782bbccca9SAdam Balogh isWithinConstantOverflowBounds(Int))); 3792bbccca9SAdam Balogh } 3802bbccca9SAdam Balogh 3812bbccca9SAdam Balogh static Optional<NonLoc> tryRearrange(ProgramStateRef State, 3822bbccca9SAdam Balogh BinaryOperator::Opcode Op, NonLoc Lhs, 3832bbccca9SAdam Balogh NonLoc Rhs, QualType ResultTy) { 3842bbccca9SAdam Balogh ProgramStateManager &StateMgr = State->getStateManager(); 3852bbccca9SAdam Balogh SValBuilder &SVB = StateMgr.getSValBuilder(); 3862bbccca9SAdam Balogh 3872bbccca9SAdam Balogh // We expect everything to be of the same type - this type. 3882bbccca9SAdam Balogh QualType SingleTy; 3892bbccca9SAdam Balogh 390dcde8accSAdam Balogh // FIXME: After putting complexity threshold to the symbols we can always 391dcde8accSAdam Balogh // rearrange additive operations but rearrange comparisons only if 392dcde8accSAdam Balogh // option is set. 393b97a9640SBalazs Benics if (!SVB.getAnalyzerOptions().ShouldAggressivelySimplifyBinaryOperation) 394dcde8accSAdam Balogh return None; 395dcde8accSAdam Balogh 3962bbccca9SAdam Balogh SymbolRef LSym = Lhs.getAsSymbol(); 3972bbccca9SAdam Balogh if (!LSym) 3982bbccca9SAdam Balogh return None; 3992bbccca9SAdam Balogh 400dcde8accSAdam Balogh if (BinaryOperator::isComparisonOp(Op)) { 4012bbccca9SAdam Balogh SingleTy = LSym->getType(); 4022bbccca9SAdam Balogh if (ResultTy != SVB.getConditionType()) 4032bbccca9SAdam Balogh return None; 4042bbccca9SAdam Balogh // Initialize SingleTy later with a symbol's type. 4052bbccca9SAdam Balogh } else if (BinaryOperator::isAdditiveOp(Op)) { 4062bbccca9SAdam Balogh SingleTy = ResultTy; 40713e186c0SAdam Balogh if (LSym->getType() != SingleTy) 40813e186c0SAdam Balogh return None; 4092bbccca9SAdam Balogh } else { 4102bbccca9SAdam Balogh // Don't rearrange other operations. 4112bbccca9SAdam Balogh return None; 4122bbccca9SAdam Balogh } 4132bbccca9SAdam Balogh 4142bbccca9SAdam Balogh assert(!SingleTy.isNull() && "We should have figured out the type by now!"); 4152bbccca9SAdam Balogh 416471d0864SAdam Balogh // Rearrange signed symbolic expressions only 417471d0864SAdam Balogh if (!SingleTy->isSignedIntegerOrEnumerationType()) 418471d0864SAdam Balogh return None; 419471d0864SAdam Balogh 4202bbccca9SAdam Balogh SymbolRef RSym = Rhs.getAsSymbol(); 4212bbccca9SAdam Balogh if (!RSym || RSym->getType() != SingleTy) 4222bbccca9SAdam Balogh return None; 4232bbccca9SAdam Balogh 4242bbccca9SAdam Balogh BasicValueFactory &BV = State->getBasicVals(); 4252bbccca9SAdam Balogh llvm::APSInt LInt, RInt; 4262bbccca9SAdam Balogh std::tie(LSym, LInt) = decomposeSymbol(LSym, BV); 4272bbccca9SAdam Balogh std::tie(RSym, RInt) = decomposeSymbol(RSym, BV); 4282bbccca9SAdam Balogh if (!shouldRearrange(State, Op, LSym, LInt, SingleTy) || 4292bbccca9SAdam Balogh !shouldRearrange(State, Op, RSym, RInt, SingleTy)) 4302bbccca9SAdam Balogh return None; 4312bbccca9SAdam Balogh 4322bbccca9SAdam Balogh // We know that no overflows can occur anymore. 4332bbccca9SAdam Balogh return doRearrangeUnchecked(State, Op, LSym, LInt, RSym, RInt); 4342bbccca9SAdam Balogh } 4352bbccca9SAdam Balogh 43649b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state, 437fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode op, 438fa0734ecSArgyrios Kyrtzidis NonLoc lhs, NonLoc rhs, 439fa0734ecSArgyrios Kyrtzidis QualType resultTy) { 440f0e9ca86SAnna Zaks NonLoc InputLHS = lhs; 441f0e9ca86SAnna Zaks NonLoc InputRHS = rhs; 442f0e9ca86SAnna Zaks 44312887a20SGabor Marton // Constraints may have changed since the creation of a bound SVal. Check if 44412887a20SGabor Marton // the values can be simplified based on those new constraints. 44512887a20SGabor Marton SVal simplifiedLhs = simplifySVal(state, lhs); 44612887a20SGabor Marton SVal simplifiedRhs = simplifySVal(state, rhs); 44712887a20SGabor Marton if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>()) 44812887a20SGabor Marton lhs = *simplifiedLhsAsNonLoc; 44912887a20SGabor Marton if (auto simplifiedRhsAsNonLoc = simplifiedRhs.getAs<NonLoc>()) 45012887a20SGabor Marton rhs = *simplifiedRhsAsNonLoc; 45112887a20SGabor Marton 452fa0734ecSArgyrios Kyrtzidis // Handle trivial case where left-side and right-side are the same. 453fa0734ecSArgyrios Kyrtzidis if (lhs == rhs) 454fa0734ecSArgyrios Kyrtzidis switch (op) { 455fa0734ecSArgyrios Kyrtzidis default: 456fa0734ecSArgyrios Kyrtzidis break; 457fa0734ecSArgyrios Kyrtzidis case BO_EQ: 458fa0734ecSArgyrios Kyrtzidis case BO_LE: 459fa0734ecSArgyrios Kyrtzidis case BO_GE: 460fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 461fa0734ecSArgyrios Kyrtzidis case BO_LT: 462fa0734ecSArgyrios Kyrtzidis case BO_GT: 463fa0734ecSArgyrios Kyrtzidis case BO_NE: 464fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 465fa0734ecSArgyrios Kyrtzidis case BO_Xor: 466fa0734ecSArgyrios Kyrtzidis case BO_Sub: 4677523d1a8SJordan Rose if (resultTy->isIntegralOrEnumerationType()) 468fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy); 46901ddfa95SDenys Petrov return evalCast(makeIntVal(0, /*isUnsigned=*/false), resultTy, 47001ddfa95SDenys Petrov QualType{}); 471fa0734ecSArgyrios Kyrtzidis case BO_Or: 472fa0734ecSArgyrios Kyrtzidis case BO_And: 47301ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 474fa0734ecSArgyrios Kyrtzidis } 475fa0734ecSArgyrios Kyrtzidis 47640446663SKazu Hirata while (true) { 477fa0734ecSArgyrios Kyrtzidis switch (lhs.getSubKind()) { 478fa0734ecSArgyrios Kyrtzidis default: 479bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, lhs, rhs, resultTy); 48064c01f7bSDevin Coughlin case nonloc::PointerToMemberKind: { 48164c01f7bSDevin Coughlin assert(rhs.getSubKind() == nonloc::PointerToMemberKind && 48264c01f7bSDevin Coughlin "Both SVals should have pointer-to-member-type"); 48364c01f7bSDevin Coughlin auto LPTM = lhs.castAs<nonloc::PointerToMember>(), 48464c01f7bSDevin Coughlin RPTM = rhs.castAs<nonloc::PointerToMember>(); 48564c01f7bSDevin Coughlin auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData(); 48664c01f7bSDevin Coughlin switch (op) { 48764c01f7bSDevin Coughlin case BO_EQ: 48864c01f7bSDevin Coughlin return makeTruthVal(LPTMD == RPTMD, resultTy); 48964c01f7bSDevin Coughlin case BO_NE: 49064c01f7bSDevin Coughlin return makeTruthVal(LPTMD != RPTMD, resultTy); 49164c01f7bSDevin Coughlin default: 49264c01f7bSDevin Coughlin return UnknownVal(); 49364c01f7bSDevin Coughlin } 49464c01f7bSDevin Coughlin } 495fa0734ecSArgyrios Kyrtzidis case nonloc::LocAsIntegerKind: { 4962fdacbc5SDavid Blaikie Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc(); 497fa0734ecSArgyrios Kyrtzidis switch (rhs.getSubKind()) { 498fa0734ecSArgyrios Kyrtzidis case nonloc::LocAsIntegerKind: 49918d77984SAlexander Shaposhnikov // FIXME: at the moment the implementation 50018d77984SAlexander Shaposhnikov // of modeling "pointers as integers" is not complete. 50118d77984SAlexander Shaposhnikov if (!BinaryOperator::isComparisonOp(op)) 50218d77984SAlexander Shaposhnikov return UnknownVal(); 503fa0734ecSArgyrios Kyrtzidis return evalBinOpLL(state, op, lhsL, 5042fdacbc5SDavid Blaikie rhs.castAs<nonloc::LocAsInteger>().getLoc(), 505fa0734ecSArgyrios Kyrtzidis resultTy); 506fa0734ecSArgyrios Kyrtzidis case nonloc::ConcreteIntKind: { 50718d77984SAlexander Shaposhnikov // FIXME: at the moment the implementation 50818d77984SAlexander Shaposhnikov // of modeling "pointers as integers" is not complete. 50918d77984SAlexander Shaposhnikov if (!BinaryOperator::isComparisonOp(op)) 51018d77984SAlexander Shaposhnikov return UnknownVal(); 511fa0734ecSArgyrios Kyrtzidis // Transform the integer into a location and compare. 5127333a9eaSArtem Dergachev // FIXME: This only makes sense for comparisons. If we want to, say, 5137333a9eaSArtem Dergachev // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it, 5147333a9eaSArtem Dergachev // then pack it back into a LocAsInteger. 5152fdacbc5SDavid Blaikie llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue(); 51627ed855aSDavid Stenberg // If the region has a symbolic base, pay attention to the type; it 51727ed855aSDavid Stenberg // might be coming from a non-default address space. For non-symbolic 51827ed855aSDavid Stenberg // regions it doesn't matter that much because such comparisons would 51927ed855aSDavid Stenberg // most likely evaluate to concrete false anyway. FIXME: We might 52027ed855aSDavid Stenberg // still need to handle the non-comparison case. 52127ed855aSDavid Stenberg if (SymbolRef lSym = lhs.getAsLocSymbol(true)) 52227ed855aSDavid Stenberg BasicVals.getAPSIntType(lSym->getType()).apply(i); 52327ed855aSDavid Stenberg else 5247e3c3ea3SJordy Rose BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i); 525fa0734ecSArgyrios Kyrtzidis return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy); 526fa0734ecSArgyrios Kyrtzidis } 527fa0734ecSArgyrios Kyrtzidis default: 528fa0734ecSArgyrios Kyrtzidis switch (op) { 529fa0734ecSArgyrios Kyrtzidis case BO_EQ: 530fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 531fa0734ecSArgyrios Kyrtzidis case BO_NE: 532fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 533fa0734ecSArgyrios Kyrtzidis default: 534fa0734ecSArgyrios Kyrtzidis // This case also handles pointer arithmetic. 535bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy); 536fa0734ecSArgyrios Kyrtzidis } 537fa0734ecSArgyrios Kyrtzidis } 538fa0734ecSArgyrios Kyrtzidis } 539d066f79cSAnna Zaks case nonloc::ConcreteIntKind: { 5402fdacbc5SDavid Blaikie llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue(); 541d066f79cSAnna Zaks 54254569448SJordy Rose // If we're dealing with two known constants, just perform the operation. 543*bc2c759aSGabor Marton if (const llvm::APSInt *KnownRHSValue = getConstValue(state, rhs)) { 54454569448SJordy Rose llvm::APSInt RHSValue = *KnownRHSValue; 54554569448SJordy Rose if (BinaryOperator::isComparisonOp(op)) { 54654569448SJordy Rose // We're looking for a type big enough to compare the two values. 5477e3c3ea3SJordy Rose // FIXME: This is not correct. char + short will result in a promotion 5487e3c3ea3SJordy Rose // to int. Unfortunately we have lost types by this point. 5497e3c3ea3SJordy Rose APSIntType CompareType = std::max(APSIntType(LHSValue), 5507e3c3ea3SJordy Rose APSIntType(RHSValue)); 5517e3c3ea3SJordy Rose CompareType.apply(LHSValue); 5527e3c3ea3SJordy Rose CompareType.apply(RHSValue); 55354569448SJordy Rose } else if (!BinaryOperator::isShiftOp(op)) { 5547e3c3ea3SJordy Rose APSIntType IntType = BasicVals.getAPSIntType(resultTy); 5557e3c3ea3SJordy Rose IntType.apply(LHSValue); 5567e3c3ea3SJordy Rose IntType.apply(RHSValue); 557d066f79cSAnna Zaks } 558d066f79cSAnna Zaks 55954569448SJordy Rose const llvm::APSInt *Result = 56054569448SJordy Rose BasicVals.evalAPSInt(op, LHSValue, RHSValue); 56154569448SJordy Rose if (!Result) 56254569448SJordy Rose return UndefinedVal(); 56354569448SJordy Rose 56454569448SJordy Rose return nonloc::ConcreteInt(*Result); 56554569448SJordy Rose } 566d066f79cSAnna Zaks 567d066f79cSAnna Zaks // Swap the left and right sides and flip the operator if doing so 568d066f79cSAnna Zaks // allows us to better reason about the expression (this is a form 569d066f79cSAnna Zaks // of expression canonicalization). 570d066f79cSAnna Zaks // While we're at it, catch some special cases for non-commutative ops. 571d066f79cSAnna Zaks switch (op) { 572d066f79cSAnna Zaks case BO_LT: 573d066f79cSAnna Zaks case BO_GT: 574d066f79cSAnna Zaks case BO_LE: 575d066f79cSAnna Zaks case BO_GE: 576604d0bbbSJordan Rose op = BinaryOperator::reverseComparisonOp(op); 5774dc0b1acSReid Kleckner LLVM_FALLTHROUGH; 578d066f79cSAnna Zaks case BO_EQ: 579d066f79cSAnna Zaks case BO_NE: 580d066f79cSAnna Zaks case BO_Add: 581d066f79cSAnna Zaks case BO_Mul: 582d066f79cSAnna Zaks case BO_And: 583d066f79cSAnna Zaks case BO_Xor: 584d066f79cSAnna Zaks case BO_Or: 58554569448SJordy Rose std::swap(lhs, rhs); 586d066f79cSAnna Zaks continue; 587d066f79cSAnna Zaks case BO_Shr: 58854569448SJordy Rose // (~0)>>a 589d933adeaSJay Foad if (LHSValue.isAllOnes() && LHSValue.isSigned()) 59001ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 5914dc0b1acSReid Kleckner LLVM_FALLTHROUGH; 592d066f79cSAnna Zaks case BO_Shl: 59354569448SJordy Rose // 0<<a and 0>>a 59454569448SJordy Rose if (LHSValue == 0) 59501ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 596bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy); 597015c3988SGabor Marton case BO_Div: 598015c3988SGabor Marton // 0 / x == 0 59973c120a9SValeriy Savchenko case BO_Rem: 60073c120a9SValeriy Savchenko // 0 % x == 0 60173c120a9SValeriy Savchenko if (LHSValue == 0) 60273c120a9SValeriy Savchenko return makeZeroVal(resultTy); 60373c120a9SValeriy Savchenko LLVM_FALLTHROUGH; 604d066f79cSAnna Zaks default: 605bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy); 606d066f79cSAnna Zaks } 607d066f79cSAnna Zaks } 608d066f79cSAnna Zaks case nonloc::SymbolValKind: { 60954569448SJordy Rose // We only handle LHS as simple symbols or SymIntExprs. 6102fdacbc5SDavid Blaikie SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol(); 611d066f79cSAnna Zaks 612d066f79cSAnna Zaks // LHS is a symbolic expression. 61354569448SJordy Rose if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) { 614fa0734ecSArgyrios Kyrtzidis 615fa0734ecSArgyrios Kyrtzidis // Is this a logical not? (!x is represented as x == 0.) 616fa0734ecSArgyrios Kyrtzidis if (op == BO_EQ && rhs.isZeroConstant()) { 617fa0734ecSArgyrios Kyrtzidis // We know how to negate certain expressions. Simplify them here. 618fa0734ecSArgyrios Kyrtzidis 619fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode opc = symIntExpr->getOpcode(); 620fa0734ecSArgyrios Kyrtzidis switch (opc) { 621fa0734ecSArgyrios Kyrtzidis default: 622fa0734ecSArgyrios Kyrtzidis // We don't know how to negate this operation. 623fa0734ecSArgyrios Kyrtzidis // Just handle it as if it were a normal comparison to 0. 624fa0734ecSArgyrios Kyrtzidis break; 625fa0734ecSArgyrios Kyrtzidis case BO_LAnd: 626fa0734ecSArgyrios Kyrtzidis case BO_LOr: 62783d382b1SDavid Blaikie llvm_unreachable("Logical operators handled by branching logic."); 628fa0734ecSArgyrios Kyrtzidis case BO_Assign: 629fa0734ecSArgyrios Kyrtzidis case BO_MulAssign: 630fa0734ecSArgyrios Kyrtzidis case BO_DivAssign: 631fa0734ecSArgyrios Kyrtzidis case BO_RemAssign: 632fa0734ecSArgyrios Kyrtzidis case BO_AddAssign: 633fa0734ecSArgyrios Kyrtzidis case BO_SubAssign: 634fa0734ecSArgyrios Kyrtzidis case BO_ShlAssign: 635fa0734ecSArgyrios Kyrtzidis case BO_ShrAssign: 636fa0734ecSArgyrios Kyrtzidis case BO_AndAssign: 637fa0734ecSArgyrios Kyrtzidis case BO_XorAssign: 638fa0734ecSArgyrios Kyrtzidis case BO_OrAssign: 639fa0734ecSArgyrios Kyrtzidis case BO_Comma: 64083d382b1SDavid Blaikie llvm_unreachable("'=' and ',' operators handled by ExprEngine."); 641fa0734ecSArgyrios Kyrtzidis case BO_PtrMemD: 642fa0734ecSArgyrios Kyrtzidis case BO_PtrMemI: 64383d382b1SDavid Blaikie llvm_unreachable("Pointer arithmetic not handled here."); 644fa0734ecSArgyrios Kyrtzidis case BO_LT: 645fa0734ecSArgyrios Kyrtzidis case BO_GT: 646fa0734ecSArgyrios Kyrtzidis case BO_LE: 647fa0734ecSArgyrios Kyrtzidis case BO_GE: 648fa0734ecSArgyrios Kyrtzidis case BO_EQ: 649fa0734ecSArgyrios Kyrtzidis case BO_NE: 650dc16628cSJordan Rose assert(resultTy->isBooleanType() || 651dc16628cSJordan Rose resultTy == getConditionType()); 652dc16628cSJordan Rose assert(symIntExpr->getType()->isBooleanType() || 653dc16628cSJordan Rose getContext().hasSameUnqualifiedType(symIntExpr->getType(), 654dc16628cSJordan Rose getConditionType())); 655fa0734ecSArgyrios Kyrtzidis // Negate the comparison and make a value. 656604d0bbbSJordan Rose opc = BinaryOperator::negateComparisonOp(opc); 657fa0734ecSArgyrios Kyrtzidis return makeNonLoc(symIntExpr->getLHS(), opc, 658fa0734ecSArgyrios Kyrtzidis symIntExpr->getRHS(), resultTy); 659fa0734ecSArgyrios Kyrtzidis } 660fa0734ecSArgyrios Kyrtzidis } 661fa0734ecSArgyrios Kyrtzidis 662fa0734ecSArgyrios Kyrtzidis // For now, only handle expressions whose RHS is a constant. 663*bc2c759aSGabor Marton if (const llvm::APSInt *RHSValue = getConstValue(state, rhs)) { 664fa0734ecSArgyrios Kyrtzidis // If both the LHS and the current expression are additive, 66554569448SJordy Rose // fold their constants and try again. 666fa0734ecSArgyrios Kyrtzidis if (BinaryOperator::isAdditiveOp(op)) { 667fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode lop = symIntExpr->getOpcode(); 668fa0734ecSArgyrios Kyrtzidis if (BinaryOperator::isAdditiveOp(lop)) { 66954569448SJordy Rose // Convert the two constants to a common type, then combine them. 67054569448SJordy Rose 671fa0734ecSArgyrios Kyrtzidis // resultTy may not be the best type to convert to, but it's 672fa0734ecSArgyrios Kyrtzidis // probably the best choice in expressions with mixed type 673fa0734ecSArgyrios Kyrtzidis // (such as x+1U+2LL). The rules for implicit conversions should 674fa0734ecSArgyrios Kyrtzidis // choose a reasonable type to preserve the expression, and will 675fa0734ecSArgyrios Kyrtzidis // at least match how the value is going to be used. 6767e3c3ea3SJordy Rose APSIntType IntType = BasicVals.getAPSIntType(resultTy); 6777e3c3ea3SJordy Rose const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS()); 6787e3c3ea3SJordy Rose const llvm::APSInt &second = IntType.convert(*RHSValue); 67954569448SJordy Rose 68014742443STomasz Kamiński // If the op and lop agrees, then we just need to 68114742443STomasz Kamiński // sum the constants. Otherwise, we change to operation 68214742443STomasz Kamiński // type if substraction would produce negative value 68314742443STomasz Kamiński // (and cause overflow for unsigned integers), 68414742443STomasz Kamiński // as consequence x+1U-10 produces x-9U, instead 68514742443STomasz Kamiński // of x+4294967287U, that would be produced without this 68614742443STomasz Kamiński // additional check. 687fa0734ecSArgyrios Kyrtzidis const llvm::APSInt *newRHS; 68814742443STomasz Kamiński if (lop == op) { 689fa0734ecSArgyrios Kyrtzidis newRHS = BasicVals.evalAPSInt(BO_Add, first, second); 69014742443STomasz Kamiński } else if (first >= second) { 691fa0734ecSArgyrios Kyrtzidis newRHS = BasicVals.evalAPSInt(BO_Sub, first, second); 69214742443STomasz Kamiński op = lop; 69314742443STomasz Kamiński } else { 69414742443STomasz Kamiński newRHS = BasicVals.evalAPSInt(BO_Sub, second, first); 69514742443STomasz Kamiński } 69654569448SJordy Rose 69754569448SJordy Rose assert(newRHS && "Invalid operation despite common type!"); 69854569448SJordy Rose rhs = nonloc::ConcreteInt(*newRHS); 69954569448SJordy Rose lhs = nonloc::SymbolVal(symIntExpr->getLHS()); 70054569448SJordy Rose continue; 701fa0734ecSArgyrios Kyrtzidis } 702fa0734ecSArgyrios Kyrtzidis } 703fa0734ecSArgyrios Kyrtzidis 70454569448SJordy Rose // Otherwise, make a SymIntExpr out of the expression. 70554569448SJordy Rose return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy); 70654569448SJordy Rose } 7073b4c3ea2SJordan Rose } 708fa0734ecSArgyrios Kyrtzidis 70954569448SJordy Rose // Is the RHS a constant? 710*bc2c759aSGabor Marton if (const llvm::APSInt *RHSValue = getConstValue(state, rhs)) 71154569448SJordy Rose return MakeSymIntVal(Sym, op, *RHSValue, resultTy); 712fa0734ecSArgyrios Kyrtzidis 7132bbccca9SAdam Balogh if (Optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy)) 7142bbccca9SAdam Balogh return *V; 7152bbccca9SAdam Balogh 71654569448SJordy Rose // Give up -- this is not a symbolic expression we can handle. 717bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy); 718fa0734ecSArgyrios Kyrtzidis } 719fa0734ecSArgyrios Kyrtzidis } 720fa0734ecSArgyrios Kyrtzidis } 721fa0734ecSArgyrios Kyrtzidis } 722fa0734ecSArgyrios Kyrtzidis 723bac964e1SAnna Zaks static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR, 724bac964e1SAnna Zaks const FieldRegion *RightFR, 725bac964e1SAnna Zaks BinaryOperator::Opcode op, 726bac964e1SAnna Zaks QualType resultTy, 727bac964e1SAnna Zaks SimpleSValBuilder &SVB) { 728bac964e1SAnna Zaks // Only comparisons are meaningful here! 729bac964e1SAnna Zaks if (!BinaryOperator::isComparisonOp(op)) 730bac964e1SAnna Zaks return UnknownVal(); 731bac964e1SAnna Zaks 732bac964e1SAnna Zaks // Next, see if the two FRs have the same super-region. 733bac964e1SAnna Zaks // FIXME: This doesn't handle casts yet, and simply stripping the casts 734bac964e1SAnna Zaks // doesn't help. 735bac964e1SAnna Zaks if (LeftFR->getSuperRegion() != RightFR->getSuperRegion()) 736bac964e1SAnna Zaks return UnknownVal(); 737bac964e1SAnna Zaks 738bac964e1SAnna Zaks const FieldDecl *LeftFD = LeftFR->getDecl(); 739bac964e1SAnna Zaks const FieldDecl *RightFD = RightFR->getDecl(); 740bac964e1SAnna Zaks const RecordDecl *RD = LeftFD->getParent(); 741bac964e1SAnna Zaks 742bac964e1SAnna Zaks // Make sure the two FRs are from the same kind of record. Just in case! 743bac964e1SAnna Zaks // FIXME: This is probably where inheritance would be a problem. 744bac964e1SAnna Zaks if (RD != RightFD->getParent()) 745bac964e1SAnna Zaks return UnknownVal(); 746bac964e1SAnna Zaks 747bac964e1SAnna Zaks // We know for sure that the two fields are not the same, since that 748bac964e1SAnna Zaks // would have given us the same SVal. 749bac964e1SAnna Zaks if (op == BO_EQ) 750bac964e1SAnna Zaks return SVB.makeTruthVal(false, resultTy); 751bac964e1SAnna Zaks if (op == BO_NE) 752bac964e1SAnna Zaks return SVB.makeTruthVal(true, resultTy); 753bac964e1SAnna Zaks 754bac964e1SAnna Zaks // Iterate through the fields and see which one comes first. 755bac964e1SAnna Zaks // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field 756bac964e1SAnna Zaks // members and the units in which bit-fields reside have addresses that 757bac964e1SAnna Zaks // increase in the order in which they are declared." 758bac964e1SAnna Zaks bool leftFirst = (op == BO_LT || op == BO_LE); 759e8a8baefSAaron Ballman for (const auto *I : RD->fields()) { 760e8a8baefSAaron Ballman if (I == LeftFD) 761bac964e1SAnna Zaks return SVB.makeTruthVal(leftFirst, resultTy); 762e8a8baefSAaron Ballman if (I == RightFD) 763bac964e1SAnna Zaks return SVB.makeTruthVal(!leftFirst, resultTy); 764bac964e1SAnna Zaks } 765bac964e1SAnna Zaks 766bac964e1SAnna Zaks llvm_unreachable("Fields not found in parent record's definition"); 767bac964e1SAnna Zaks } 768bac964e1SAnna Zaks 7694d5b824eSVince Bridgers // This is used in debug builds only for now because some downstream users 7704d5b824eSVince Bridgers // may hit this assert in their subsequent merges. 7714d5b824eSVince Bridgers // There are still places in the analyzer where equal bitwidth Locs 7724d5b824eSVince Bridgers // are compared, and need to be found and corrected. Recent previous fixes have 7734d5b824eSVince Bridgers // addressed the known problems of making NULLs with specific bitwidths 7744d5b824eSVince Bridgers // for Loc comparisons along with deprecation of APIs for the same purpose. 7754d5b824eSVince Bridgers // 7764d5b824eSVince Bridgers static void assertEqualBitWidths(ProgramStateRef State, Loc RhsLoc, 7774d5b824eSVince Bridgers Loc LhsLoc) { 7784d5b824eSVince Bridgers // Implements a "best effort" check for RhsLoc and LhsLoc bit widths 7794d5b824eSVince Bridgers ASTContext &Ctx = State->getStateManager().getContext(); 7804d5b824eSVince Bridgers uint64_t RhsBitwidth = 7814d5b824eSVince Bridgers RhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(RhsLoc.getType(Ctx)); 7824d5b824eSVince Bridgers uint64_t LhsBitwidth = 7834d5b824eSVince Bridgers LhsLoc.getType(Ctx).isNull() ? 0 : Ctx.getTypeSize(LhsLoc.getType(Ctx)); 7844d5b824eSVince Bridgers if (RhsBitwidth && LhsBitwidth && 7854d5b824eSVince Bridgers (LhsLoc.getSubKind() == RhsLoc.getSubKind())) { 7864d5b824eSVince Bridgers assert(RhsBitwidth == LhsBitwidth && 7874d5b824eSVince Bridgers "RhsLoc and LhsLoc bitwidth must be same!"); 7884d5b824eSVince Bridgers } 7894d5b824eSVince Bridgers } 7904d5b824eSVince Bridgers 791fa0734ecSArgyrios Kyrtzidis // FIXME: all this logic will change if/when we have MemRegion::getLocation(). 79249b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state, 793fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode op, 794fa0734ecSArgyrios Kyrtzidis Loc lhs, Loc rhs, 795fa0734ecSArgyrios Kyrtzidis QualType resultTy) { 7964d5b824eSVince Bridgers 7974d5b824eSVince Bridgers // Assert that bitwidth of lhs and rhs are the same. 7984d5b824eSVince Bridgers // This can happen if two different address spaces are used, 7994d5b824eSVince Bridgers // and the bitwidths of the address spaces are different. 8004d5b824eSVince Bridgers // See LIT case clang/test/Analysis/cstring-checker-addressspace.c 8014d5b824eSVince Bridgers // FIXME: See comment above in the function assertEqualBitWidths 8024d5b824eSVince Bridgers assertEqualBitWidths(state, rhs, lhs); 8034d5b824eSVince Bridgers 804fa0734ecSArgyrios Kyrtzidis // Only comparisons and subtractions are valid operations on two pointers. 805fa0734ecSArgyrios Kyrtzidis // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15]. 806fa0734ecSArgyrios Kyrtzidis // However, if a pointer is casted to an integer, evalBinOpNN may end up 807fa0734ecSArgyrios Kyrtzidis // calling this function with another operation (PR7527). We don't attempt to 808fa0734ecSArgyrios Kyrtzidis // model this for now, but it could be useful, particularly when the 809fa0734ecSArgyrios Kyrtzidis // "location" is actually an integer value that's been passed through a void*. 810fa0734ecSArgyrios Kyrtzidis if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub)) 811fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 812fa0734ecSArgyrios Kyrtzidis 813fa0734ecSArgyrios Kyrtzidis // Special cases for when both sides are identical. 814fa0734ecSArgyrios Kyrtzidis if (lhs == rhs) { 815fa0734ecSArgyrios Kyrtzidis switch (op) { 816fa0734ecSArgyrios Kyrtzidis default: 81783d382b1SDavid Blaikie llvm_unreachable("Unimplemented operation for two identical values"); 818fa0734ecSArgyrios Kyrtzidis case BO_Sub: 819fa0734ecSArgyrios Kyrtzidis return makeZeroVal(resultTy); 820fa0734ecSArgyrios Kyrtzidis case BO_EQ: 821fa0734ecSArgyrios Kyrtzidis case BO_LE: 822fa0734ecSArgyrios Kyrtzidis case BO_GE: 823fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 824fa0734ecSArgyrios Kyrtzidis case BO_NE: 825fa0734ecSArgyrios Kyrtzidis case BO_LT: 826fa0734ecSArgyrios Kyrtzidis case BO_GT: 827fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 828fa0734ecSArgyrios Kyrtzidis } 829fa0734ecSArgyrios Kyrtzidis } 830fa0734ecSArgyrios Kyrtzidis 831fa0734ecSArgyrios Kyrtzidis switch (lhs.getSubKind()) { 832fa0734ecSArgyrios Kyrtzidis default: 83383d382b1SDavid Blaikie llvm_unreachable("Ordering not implemented for this Loc."); 834fa0734ecSArgyrios Kyrtzidis 835fa0734ecSArgyrios Kyrtzidis case loc::GotoLabelKind: 836fa0734ecSArgyrios Kyrtzidis // The only thing we know about labels is that they're non-null. 837fa0734ecSArgyrios Kyrtzidis if (rhs.isZeroConstant()) { 838fa0734ecSArgyrios Kyrtzidis switch (op) { 839fa0734ecSArgyrios Kyrtzidis default: 840fa0734ecSArgyrios Kyrtzidis break; 841fa0734ecSArgyrios Kyrtzidis case BO_Sub: 84201ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 843fa0734ecSArgyrios Kyrtzidis case BO_EQ: 844fa0734ecSArgyrios Kyrtzidis case BO_LE: 845fa0734ecSArgyrios Kyrtzidis case BO_LT: 846fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 847fa0734ecSArgyrios Kyrtzidis case BO_NE: 848fa0734ecSArgyrios Kyrtzidis case BO_GT: 849fa0734ecSArgyrios Kyrtzidis case BO_GE: 850fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 851fa0734ecSArgyrios Kyrtzidis } 852fa0734ecSArgyrios Kyrtzidis } 853fa0734ecSArgyrios Kyrtzidis // There may be two labels for the same location, and a function region may 854fa0734ecSArgyrios Kyrtzidis // have the same address as a label at the start of the function (depending 855fa0734ecSArgyrios Kyrtzidis // on the ABI). 856fa0734ecSArgyrios Kyrtzidis // FIXME: we can probably do a comparison against other MemRegions, though. 857fa0734ecSArgyrios Kyrtzidis // FIXME: is there a way to tell if two labels refer to the same location? 858fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 859fa0734ecSArgyrios Kyrtzidis 860fa0734ecSArgyrios Kyrtzidis case loc::ConcreteIntKind: { 861f6eab437SBalazs Benics auto L = lhs.castAs<loc::ConcreteInt>(); 862f6eab437SBalazs Benics 863fa0734ecSArgyrios Kyrtzidis // If one of the operands is a symbol and the other is a constant, 864fa0734ecSArgyrios Kyrtzidis // build an expression for use by the constraint manager. 865fa0734ecSArgyrios Kyrtzidis if (SymbolRef rSym = rhs.getAsLocSymbol()) { 866c0402c69SDominic Chen // We can only build expressions with symbols on the left, 867c0402c69SDominic Chen // so we need a reversible operator. 868c70f1d63SRichard Smith if (!BinaryOperator::isComparisonOp(op) || op == BO_Cmp) 869c0402c69SDominic Chen return UnknownVal(); 87035610d21SDominic Chen 871604d0bbbSJordan Rose op = BinaryOperator::reverseComparisonOp(op); 872f6eab437SBalazs Benics return makeNonLoc(rSym, op, L.getValue(), resultTy); 873fa0734ecSArgyrios Kyrtzidis } 874fa0734ecSArgyrios Kyrtzidis 875fa0734ecSArgyrios Kyrtzidis // If both operands are constants, just perform the operation. 87605785d16SDavid Blaikie if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) { 877f6eab437SBalazs Benics assert(BinaryOperator::isComparisonOp(op) || op == BO_Sub); 8788eca04b2SJordan Rose 879f6eab437SBalazs Benics if (const auto *ResultInt = 880f6eab437SBalazs Benics BasicVals.evalAPSInt(op, L.getValue(), rInt->getValue())) 881f6eab437SBalazs Benics return evalCast(nonloc::ConcreteInt(*ResultInt), resultTy, QualType{}); 882fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 883fa0734ecSArgyrios Kyrtzidis } 884fa0734ecSArgyrios Kyrtzidis 885fa0734ecSArgyrios Kyrtzidis // Special case comparisons against NULL. 886fa0734ecSArgyrios Kyrtzidis // This must come after the test if the RHS is a symbol, which is used to 887fa0734ecSArgyrios Kyrtzidis // build constraints. The address of any non-symbolic region is guaranteed 888fa0734ecSArgyrios Kyrtzidis // to be non-NULL, as is any label. 8892fdacbc5SDavid Blaikie assert(rhs.getAs<loc::MemRegionVal>() || rhs.getAs<loc::GotoLabel>()); 890fa0734ecSArgyrios Kyrtzidis if (lhs.isZeroConstant()) { 891fa0734ecSArgyrios Kyrtzidis switch (op) { 892fa0734ecSArgyrios Kyrtzidis default: 893fa0734ecSArgyrios Kyrtzidis break; 894fa0734ecSArgyrios Kyrtzidis case BO_EQ: 895fa0734ecSArgyrios Kyrtzidis case BO_GT: 896fa0734ecSArgyrios Kyrtzidis case BO_GE: 897fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 898fa0734ecSArgyrios Kyrtzidis case BO_NE: 899fa0734ecSArgyrios Kyrtzidis case BO_LT: 900fa0734ecSArgyrios Kyrtzidis case BO_LE: 901fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 902fa0734ecSArgyrios Kyrtzidis } 903fa0734ecSArgyrios Kyrtzidis } 904fa0734ecSArgyrios Kyrtzidis 905fa0734ecSArgyrios Kyrtzidis // Comparing an arbitrary integer to a region or label address is 906fa0734ecSArgyrios Kyrtzidis // completely unknowable. 907fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 908fa0734ecSArgyrios Kyrtzidis } 90973f018e3SArtem Dergachev case loc::MemRegionValKind: { 91005785d16SDavid Blaikie if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) { 911fa0734ecSArgyrios Kyrtzidis // If one of the operands is a symbol and the other is a constant, 912fa0734ecSArgyrios Kyrtzidis // build an expression for use by the constraint manager. 913f4963ff1SAlexander Shaposhnikov if (SymbolRef lSym = lhs.getAsLocSymbol(true)) { 914f4963ff1SAlexander Shaposhnikov if (BinaryOperator::isComparisonOp(op)) 915fa0734ecSArgyrios Kyrtzidis return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy); 916f4963ff1SAlexander Shaposhnikov return UnknownVal(); 917f4963ff1SAlexander Shaposhnikov } 918fa0734ecSArgyrios Kyrtzidis // Special case comparisons to NULL. 919fa0734ecSArgyrios Kyrtzidis // This must come after the test if the LHS is a symbol, which is used to 920fa0734ecSArgyrios Kyrtzidis // build constraints. The address of any non-symbolic region is guaranteed 921fa0734ecSArgyrios Kyrtzidis // to be non-NULL. 922fa0734ecSArgyrios Kyrtzidis if (rInt->isZeroConstant()) { 923acd080b9SJordan Rose if (op == BO_Sub) 92401ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 925acd080b9SJordan Rose 926acd080b9SJordan Rose if (BinaryOperator::isComparisonOp(op)) { 927acd080b9SJordan Rose QualType boolType = getContext().BoolTy; 92801ddfa95SDenys Petrov NonLoc l = evalCast(lhs, boolType, QualType{}).castAs<NonLoc>(); 929acd080b9SJordan Rose NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>(); 930acd080b9SJordan Rose return evalBinOpNN(state, op, l, r, resultTy); 931fa0734ecSArgyrios Kyrtzidis } 932fa0734ecSArgyrios Kyrtzidis } 933fa0734ecSArgyrios Kyrtzidis 934fa0734ecSArgyrios Kyrtzidis // Comparing a region to an arbitrary integer is completely unknowable. 935fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 936fa0734ecSArgyrios Kyrtzidis } 937fa0734ecSArgyrios Kyrtzidis 938fa0734ecSArgyrios Kyrtzidis // Get both values as regions, if possible. 939fa0734ecSArgyrios Kyrtzidis const MemRegion *LeftMR = lhs.getAsRegion(); 94073f018e3SArtem Dergachev assert(LeftMR && "MemRegionValKind SVal doesn't have a region!"); 941fa0734ecSArgyrios Kyrtzidis 942fa0734ecSArgyrios Kyrtzidis const MemRegion *RightMR = rhs.getAsRegion(); 943fa0734ecSArgyrios Kyrtzidis if (!RightMR) 944fa0734ecSArgyrios Kyrtzidis // The RHS is probably a label, which in theory could address a region. 945fa0734ecSArgyrios Kyrtzidis // FIXME: we can probably make a more useful statement about non-code 946fa0734ecSArgyrios Kyrtzidis // regions, though. 947fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 948fa0734ecSArgyrios Kyrtzidis 949fa0734ecSArgyrios Kyrtzidis const MemRegion *LeftBase = LeftMR->getBaseRegion(); 950fa0734ecSArgyrios Kyrtzidis const MemRegion *RightBase = RightMR->getBaseRegion(); 9513b4c3ea2SJordan Rose const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace(); 9523b4c3ea2SJordan Rose const MemSpaceRegion *RightMS = RightBase->getMemorySpace(); 9533b4c3ea2SJordan Rose const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion(); 9543563fde6SAnna Zaks 9553563fde6SAnna Zaks // If the two regions are from different known memory spaces they cannot be 9563563fde6SAnna Zaks // equal. Also, assume that no symbolic region (whose memory space is 9573563fde6SAnna Zaks // unknown) is on the stack. 9583563fde6SAnna Zaks if (LeftMS != RightMS && 9593563fde6SAnna Zaks ((LeftMS != UnknownMS && RightMS != UnknownMS) || 9603563fde6SAnna Zaks (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) { 961fa0734ecSArgyrios Kyrtzidis switch (op) { 962fa0734ecSArgyrios Kyrtzidis default: 963fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 964fa0734ecSArgyrios Kyrtzidis case BO_EQ: 965fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 966fa0734ecSArgyrios Kyrtzidis case BO_NE: 967fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 968fa0734ecSArgyrios Kyrtzidis } 969fa0734ecSArgyrios Kyrtzidis } 970fa0734ecSArgyrios Kyrtzidis 9713563fde6SAnna Zaks // If both values wrap regions, see if they're from different base regions. 9723563fde6SAnna Zaks // Note, heap base symbolic regions are assumed to not alias with 9733563fde6SAnna Zaks // each other; for example, we assume that malloc returns different address 9743563fde6SAnna Zaks // on each invocation. 975aacc03c9SArtem Dergachev // FIXME: ObjC object pointers always reside on the heap, but currently 976aacc03c9SArtem Dergachev // we treat their memory space as unknown, because symbolic pointers 977aacc03c9SArtem Dergachev // to ObjC objects may alias. There should be a way to construct 978aacc03c9SArtem Dergachev // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker 979aacc03c9SArtem Dergachev // guesses memory space for ObjC object pointers manually instead of 980aacc03c9SArtem Dergachev // relying on us. 9813563fde6SAnna Zaks if (LeftBase != RightBase && 9823563fde6SAnna Zaks ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) || 983a7dcc996SAnna Zaks (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){ 9849d96f843STed Kremenek switch (op) { 9859d96f843STed Kremenek default: 9863563fde6SAnna Zaks return UnknownVal(); 9879d96f843STed Kremenek case BO_EQ: 9889d96f843STed Kremenek return makeTruthVal(false, resultTy); 9899d96f843STed Kremenek case BO_NE: 9909d96f843STed Kremenek return makeTruthVal(true, resultTy); 9919d96f843STed Kremenek } 9929d96f843STed Kremenek } 993fa0734ecSArgyrios Kyrtzidis 994bac964e1SAnna Zaks // Handle special cases for when both regions are element regions. 995fa0734ecSArgyrios Kyrtzidis const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR); 996bac964e1SAnna Zaks const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR); 997bac964e1SAnna Zaks if (RightER && LeftER) { 998fa0734ecSArgyrios Kyrtzidis // Next, see if the two ERs have the same super-region and matching types. 999fa0734ecSArgyrios Kyrtzidis // FIXME: This should do something useful even if the types don't match, 1000fa0734ecSArgyrios Kyrtzidis // though if both indexes are constant the RegionRawOffset path will 1001fa0734ecSArgyrios Kyrtzidis // give the correct answer. 1002fa0734ecSArgyrios Kyrtzidis if (LeftER->getSuperRegion() == RightER->getSuperRegion() && 1003fa0734ecSArgyrios Kyrtzidis LeftER->getElementType() == RightER->getElementType()) { 1004fa0734ecSArgyrios Kyrtzidis // Get the left index and cast it to the correct type. 1005fa0734ecSArgyrios Kyrtzidis // If the index is unknown or undefined, bail out here. 1006fa0734ecSArgyrios Kyrtzidis SVal LeftIndexVal = LeftER->getIndex(); 100705785d16SDavid Blaikie Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>(); 1008fa0734ecSArgyrios Kyrtzidis if (!LeftIndex) 1009fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 101001ddfa95SDenys Petrov LeftIndexVal = evalCast(*LeftIndex, ArrayIndexTy, QualType{}); 10112fdacbc5SDavid Blaikie LeftIndex = LeftIndexVal.getAs<NonLoc>(); 1012fa0734ecSArgyrios Kyrtzidis if (!LeftIndex) 1013fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 1014fa0734ecSArgyrios Kyrtzidis 1015fa0734ecSArgyrios Kyrtzidis // Do the same for the right index. 1016fa0734ecSArgyrios Kyrtzidis SVal RightIndexVal = RightER->getIndex(); 101705785d16SDavid Blaikie Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>(); 1018fa0734ecSArgyrios Kyrtzidis if (!RightIndex) 1019fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 102001ddfa95SDenys Petrov RightIndexVal = evalCast(*RightIndex, ArrayIndexTy, QualType{}); 10212fdacbc5SDavid Blaikie RightIndex = RightIndexVal.getAs<NonLoc>(); 1022fa0734ecSArgyrios Kyrtzidis if (!RightIndex) 1023fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 1024fa0734ecSArgyrios Kyrtzidis 1025fa0734ecSArgyrios Kyrtzidis // Actually perform the operation. 1026fa0734ecSArgyrios Kyrtzidis // evalBinOpNN expects the two indexes to already be the right type. 1027fa0734ecSArgyrios Kyrtzidis return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy); 1028fa0734ecSArgyrios Kyrtzidis } 1029bac964e1SAnna Zaks } 1030fa0734ecSArgyrios Kyrtzidis 1031bac964e1SAnna Zaks // Special handling of the FieldRegions, even with symbolic offsets. 1032bac964e1SAnna Zaks const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR); 1033bac964e1SAnna Zaks const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR); 1034bac964e1SAnna Zaks if (RightFR && LeftFR) { 1035bac964e1SAnna Zaks SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy, 1036bac964e1SAnna Zaks *this); 1037bac964e1SAnna Zaks if (!R.isUnknown()) 1038bac964e1SAnna Zaks return R; 1039bac964e1SAnna Zaks } 1040bac964e1SAnna Zaks 1041bac964e1SAnna Zaks // Compare the regions using the raw offsets. 1042bac964e1SAnna Zaks RegionOffset LeftOffset = LeftMR->getAsOffset(); 1043bac964e1SAnna Zaks RegionOffset RightOffset = RightMR->getAsOffset(); 1044fa0734ecSArgyrios Kyrtzidis 10450dbb783cSCraig Topper if (LeftOffset.getRegion() != nullptr && 1046bac964e1SAnna Zaks LeftOffset.getRegion() == RightOffset.getRegion() && 1047bac964e1SAnna Zaks !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) { 1048bac964e1SAnna Zaks int64_t left = LeftOffset.getOffset(); 1049bac964e1SAnna Zaks int64_t right = RightOffset.getOffset(); 1050fa0734ecSArgyrios Kyrtzidis 1051fa0734ecSArgyrios Kyrtzidis switch (op) { 1052fa0734ecSArgyrios Kyrtzidis default: 1053fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 1054fa0734ecSArgyrios Kyrtzidis case BO_LT: 1055fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left < right, resultTy); 1056fa0734ecSArgyrios Kyrtzidis case BO_GT: 1057fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left > right, resultTy); 1058fa0734ecSArgyrios Kyrtzidis case BO_LE: 1059fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left <= right, resultTy); 1060fa0734ecSArgyrios Kyrtzidis case BO_GE: 1061fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left >= right, resultTy); 1062fa0734ecSArgyrios Kyrtzidis case BO_EQ: 1063fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left == right, resultTy); 1064fa0734ecSArgyrios Kyrtzidis case BO_NE: 1065fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left != right, resultTy); 1066fa0734ecSArgyrios Kyrtzidis } 1067fa0734ecSArgyrios Kyrtzidis } 1068fa0734ecSArgyrios Kyrtzidis 10693b4c3ea2SJordan Rose // At this point we're not going to get a good answer, but we can try 10703b4c3ea2SJordan Rose // conjuring an expression instead. 10713b4c3ea2SJordan Rose SymbolRef LHSSym = lhs.getAsLocSymbol(); 10723b4c3ea2SJordan Rose SymbolRef RHSSym = rhs.getAsLocSymbol(); 10733b4c3ea2SJordan Rose if (LHSSym && RHSSym) 10743b4c3ea2SJordan Rose return makeNonLoc(LHSSym, op, RHSSym, resultTy); 10753b4c3ea2SJordan Rose 1076fa0734ecSArgyrios Kyrtzidis // If we get here, we have no way of comparing the regions. 1077fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 1078fa0734ecSArgyrios Kyrtzidis } 1079fa0734ecSArgyrios Kyrtzidis } 1080fa0734ecSArgyrios Kyrtzidis } 1081fa0734ecSArgyrios Kyrtzidis 108249b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state, 10839cbfdde2SValeriy Savchenko BinaryOperator::Opcode op, Loc lhs, 10849cbfdde2SValeriy Savchenko NonLoc rhs, QualType resultTy) { 108564c01f7bSDevin Coughlin if (op >= BO_PtrMemD && op <= BO_PtrMemI) { 108664c01f7bSDevin Coughlin if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) { 108764c01f7bSDevin Coughlin if (PTMSV->isNullMemberPointer()) 108864c01f7bSDevin Coughlin return UndefinedVal(); 10899cbfdde2SValeriy Savchenko 10909cbfdde2SValeriy Savchenko auto getFieldLValue = [&](const auto *FD) -> SVal { 109164c01f7bSDevin Coughlin SVal Result = lhs; 109264c01f7bSDevin Coughlin 109364c01f7bSDevin Coughlin for (const auto &I : *PTMSV) 109464c01f7bSDevin Coughlin Result = StateMgr.getStoreManager().evalDerivedToBase( 109564c01f7bSDevin Coughlin Result, I->getType(), I->isVirtual()); 10969cbfdde2SValeriy Savchenko 109764c01f7bSDevin Coughlin return state->getLValue(FD, Result); 10989cbfdde2SValeriy Savchenko }; 10999cbfdde2SValeriy Savchenko 11009cbfdde2SValeriy Savchenko if (const auto *FD = PTMSV->getDeclAs<FieldDecl>()) { 11019cbfdde2SValeriy Savchenko return getFieldLValue(FD); 11029cbfdde2SValeriy Savchenko } 11039cbfdde2SValeriy Savchenko if (const auto *FD = PTMSV->getDeclAs<IndirectFieldDecl>()) { 11049cbfdde2SValeriy Savchenko return getFieldLValue(FD); 110564c01f7bSDevin Coughlin } 110664c01f7bSDevin Coughlin } 110764c01f7bSDevin Coughlin 110864c01f7bSDevin Coughlin return rhs; 110964c01f7bSDevin Coughlin } 111064c01f7bSDevin Coughlin 1111686df322SJordan Rose assert(!BinaryOperator::isComparisonOp(op) && 1112686df322SJordan Rose "arguments to comparison ops must be of the same type"); 1113fa0734ecSArgyrios Kyrtzidis 1114fa0734ecSArgyrios Kyrtzidis // Special case: rhs is a zero constant. 1115fa0734ecSArgyrios Kyrtzidis if (rhs.isZeroConstant()) 1116fa0734ecSArgyrios Kyrtzidis return lhs; 1117fa0734ecSArgyrios Kyrtzidis 111821524676SGabor Horvath // Perserve the null pointer so that it can be found by the DerefChecker. 111921524676SGabor Horvath if (lhs.isZeroConstant()) 112021524676SGabor Horvath return lhs; 112121524676SGabor Horvath 1122fa0734ecSArgyrios Kyrtzidis // We are dealing with pointer arithmetic. 1123fa0734ecSArgyrios Kyrtzidis 1124fa0734ecSArgyrios Kyrtzidis // Handle pointer arithmetic on constant values. 112505785d16SDavid Blaikie if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) { 112605785d16SDavid Blaikie if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) { 1127fa0734ecSArgyrios Kyrtzidis const llvm::APSInt &leftI = lhsInt->getValue(); 1128fa0734ecSArgyrios Kyrtzidis assert(leftI.isUnsigned()); 1129fa0734ecSArgyrios Kyrtzidis llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true); 1130fa0734ecSArgyrios Kyrtzidis 1131fa0734ecSArgyrios Kyrtzidis // Convert the bitwidth of rightI. This should deal with overflow 1132fa0734ecSArgyrios Kyrtzidis // since we are dealing with concrete values. 1133fa0734ecSArgyrios Kyrtzidis rightI = rightI.extOrTrunc(leftI.getBitWidth()); 1134fa0734ecSArgyrios Kyrtzidis 1135fa0734ecSArgyrios Kyrtzidis // Offset the increment by the pointer size. 1136fa0734ecSArgyrios Kyrtzidis llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true); 113721524676SGabor Horvath QualType pointeeType = resultTy->getPointeeType(); 113821524676SGabor Horvath Multiplicand = getContext().getTypeSizeInChars(pointeeType).getQuantity(); 1139fa0734ecSArgyrios Kyrtzidis rightI *= Multiplicand; 1140fa0734ecSArgyrios Kyrtzidis 1141fa0734ecSArgyrios Kyrtzidis // Compute the adjusted pointer. 1142fa0734ecSArgyrios Kyrtzidis switch (op) { 1143fa0734ecSArgyrios Kyrtzidis case BO_Add: 1144fa0734ecSArgyrios Kyrtzidis rightI = leftI + rightI; 1145fa0734ecSArgyrios Kyrtzidis break; 1146fa0734ecSArgyrios Kyrtzidis case BO_Sub: 1147fa0734ecSArgyrios Kyrtzidis rightI = leftI - rightI; 1148fa0734ecSArgyrios Kyrtzidis break; 1149fa0734ecSArgyrios Kyrtzidis default: 1150fa0734ecSArgyrios Kyrtzidis llvm_unreachable("Invalid pointer arithmetic operation"); 1151fa0734ecSArgyrios Kyrtzidis } 1152fa0734ecSArgyrios Kyrtzidis return loc::ConcreteInt(getBasicValueFactory().getValue(rightI)); 1153fa0734ecSArgyrios Kyrtzidis } 1154fa0734ecSArgyrios Kyrtzidis } 1155fa0734ecSArgyrios Kyrtzidis 1156fa0734ecSArgyrios Kyrtzidis // Handle cases where 'lhs' is a region. 1157fa0734ecSArgyrios Kyrtzidis if (const MemRegion *region = lhs.getAsRegion()) { 11582fdacbc5SDavid Blaikie rhs = convertToArrayIndex(rhs).castAs<NonLoc>(); 1159fa0734ecSArgyrios Kyrtzidis SVal index = UnknownVal(); 11606dd11048SArtem Dergachev const SubRegion *superR = nullptr; 11617333a9eaSArtem Dergachev // We need to know the type of the pointer in order to add an integer to it. 11627333a9eaSArtem Dergachev // Depending on the type, different amount of bytes is added. 1163fa0734ecSArgyrios Kyrtzidis QualType elementType; 1164fa0734ecSArgyrios Kyrtzidis 1165fa0734ecSArgyrios Kyrtzidis if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) { 116657a4a152STed Kremenek assert(op == BO_Add || op == BO_Sub); 116757a4a152STed Kremenek index = evalBinOpNN(state, op, elemReg->getIndex(), rhs, 1168fa0734ecSArgyrios Kyrtzidis getArrayIndexType()); 11696dd11048SArtem Dergachev superR = cast<SubRegion>(elemReg->getSuperRegion()); 1170fa0734ecSArgyrios Kyrtzidis elementType = elemReg->getElementType(); 1171fa0734ecSArgyrios Kyrtzidis } 1172fa0734ecSArgyrios Kyrtzidis else if (isa<SubRegion>(region)) { 1173c4b28a8fSGabor Horvath assert(op == BO_Add || op == BO_Sub); 1174c4b28a8fSGabor Horvath index = (op == BO_Add) ? rhs : evalMinus(rhs); 11756dd11048SArtem Dergachev superR = cast<SubRegion>(region); 11767333a9eaSArtem Dergachev // TODO: Is this actually reliable? Maybe improving our MemRegion 11777333a9eaSArtem Dergachev // hierarchy to provide typed regions for all non-void pointers would be 11787333a9eaSArtem Dergachev // better. For instance, we cannot extend this towards LocAsInteger 11797333a9eaSArtem Dergachev // operations, where result type of the expression is integer. 1180d1a08b6eSJordan Rose if (resultTy->isAnyPointerType()) 1181d1a08b6eSJordan Rose elementType = resultTy->getPointeeType(); 1182fa0734ecSArgyrios Kyrtzidis } 1183fa0734ecSArgyrios Kyrtzidis 1184df1bb8a6SArtem Dergachev // Represent arithmetic on void pointers as arithmetic on char pointers. 1185df1bb8a6SArtem Dergachev // It is fine when a TypedValueRegion of char value type represents 1186df1bb8a6SArtem Dergachev // a void pointer. Note that arithmetic on void pointers is a GCC extension. 1187df1bb8a6SArtem Dergachev if (elementType->isVoidType()) 1188df1bb8a6SArtem Dergachev elementType = getContext().CharTy; 1189df1bb8a6SArtem Dergachev 119005785d16SDavid Blaikie if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) { 1191fa0734ecSArgyrios Kyrtzidis return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV, 1192fa0734ecSArgyrios Kyrtzidis superR, getContext())); 1193fa0734ecSArgyrios Kyrtzidis } 1194fa0734ecSArgyrios Kyrtzidis } 1195fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 1196fa0734ecSArgyrios Kyrtzidis } 1197fa0734ecSArgyrios Kyrtzidis 1198*bc2c759aSGabor Marton const llvm::APSInt *SimpleSValBuilder::getConstValue(ProgramStateRef state, 1199fa0734ecSArgyrios Kyrtzidis SVal V) { 1200fa0734ecSArgyrios Kyrtzidis if (V.isUnknownOrUndef()) 12010dbb783cSCraig Topper return nullptr; 1202fa0734ecSArgyrios Kyrtzidis 120305785d16SDavid Blaikie if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>()) 1204fa0734ecSArgyrios Kyrtzidis return &X->getValue(); 1205fa0734ecSArgyrios Kyrtzidis 120605785d16SDavid Blaikie if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>()) 1207fa0734ecSArgyrios Kyrtzidis return &X->getValue(); 1208fa0734ecSArgyrios Kyrtzidis 1209fa0734ecSArgyrios Kyrtzidis if (SymbolRef Sym = V.getAsSymbol()) 1210244e1d7dSTed Kremenek return state->getConstraintManager().getSymVal(state, Sym); 1211fa0734ecSArgyrios Kyrtzidis 12120dbb783cSCraig Topper return nullptr; 1213fa0734ecSArgyrios Kyrtzidis } 121412294f8dSArtem Dergachev 1215*bc2c759aSGabor Marton const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state, 1216*bc2c759aSGabor Marton SVal V) { 1217*bc2c759aSGabor Marton return getConstValue(state, simplifySVal(state, V)); 1218*bc2c759aSGabor Marton } 1219*bc2c759aSGabor Marton 1220978431e8SGabor Marton SVal SimpleSValBuilder::simplifyUntilFixpoint(ProgramStateRef State, SVal Val) { 1221978431e8SGabor Marton SVal SimplifiedVal = simplifySValOnce(State, Val); 1222978431e8SGabor Marton while (SimplifiedVal != Val) { 1223978431e8SGabor Marton Val = SimplifiedVal; 1224978431e8SGabor Marton SimplifiedVal = simplifySValOnce(State, Val); 1225978431e8SGabor Marton } 1226978431e8SGabor Marton return SimplifiedVal; 1227978431e8SGabor Marton } 1228978431e8SGabor Marton 122912294f8dSArtem Dergachev SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) { 1230978431e8SGabor Marton return simplifyUntilFixpoint(State, V); 1231978431e8SGabor Marton } 1232978431e8SGabor Marton 1233978431e8SGabor Marton SVal SimpleSValBuilder::simplifySValOnce(ProgramStateRef State, SVal V) { 123412294f8dSArtem Dergachev // For now, this function tries to constant-fold symbols inside a 123512294f8dSArtem Dergachev // nonloc::SymbolVal, and does nothing else. More simplifications should 123612294f8dSArtem Dergachev // be possible, such as constant-folding an index in an ElementRegion. 123712294f8dSArtem Dergachev 123812294f8dSArtem Dergachev class Simplifier : public FullSValVisitor<Simplifier, SVal> { 123912294f8dSArtem Dergachev ProgramStateRef State; 124012294f8dSArtem Dergachev SValBuilder &SVB; 124112294f8dSArtem Dergachev 124222746d7dSArtem Dergachev // Cache results for the lifetime of the Simplifier. Results change every 124322746d7dSArtem Dergachev // time new constraints are added to the program state, which is the whole 124422746d7dSArtem Dergachev // point of simplifying, and for that very reason it's pointless to maintain 124522746d7dSArtem Dergachev // the same cache for the duration of the whole analysis. 124622746d7dSArtem Dergachev llvm::DenseMap<SymbolRef, SVal> Cached; 124722746d7dSArtem Dergachev 124816a1f64cSArtem Dergachev static bool isUnchanged(SymbolRef Sym, SVal Val) { 124916a1f64cSArtem Dergachev return Sym == Val.getAsSymbol(); 125016a1f64cSArtem Dergachev } 125116a1f64cSArtem Dergachev 12529fe9a95fSArtem Dergachev SVal cache(SymbolRef Sym, SVal V) { 12539fe9a95fSArtem Dergachev Cached[Sym] = V; 12549fe9a95fSArtem Dergachev return V; 12559fe9a95fSArtem Dergachev } 12569fe9a95fSArtem Dergachev 12579fe9a95fSArtem Dergachev SVal skip(SymbolRef Sym) { 12589fe9a95fSArtem Dergachev return cache(Sym, SVB.makeSymbolVal(Sym)); 12599fe9a95fSArtem Dergachev } 12609fe9a95fSArtem Dergachev 12610a17896fSGabor Marton // Return the known const value for the Sym if available, or return Undef 12620a17896fSGabor Marton // otherwise. 12630a17896fSGabor Marton SVal getConst(SymbolRef Sym) { 12640a17896fSGabor Marton const llvm::APSInt *Const = 12650a17896fSGabor Marton State->getConstraintManager().getSymVal(State, Sym); 12660a17896fSGabor Marton if (Const) 12670a17896fSGabor Marton return Loc::isLocType(Sym->getType()) ? (SVal)SVB.makeIntLocVal(*Const) 12680a17896fSGabor Marton : (SVal)SVB.makeIntVal(*Const); 12690a17896fSGabor Marton return UndefinedVal(); 12700a17896fSGabor Marton } 12710a17896fSGabor Marton 12720a17896fSGabor Marton SVal getConstOrVisit(SymbolRef Sym) { 12730a17896fSGabor Marton const SVal Ret = getConst(Sym); 12740a17896fSGabor Marton if (Ret.isUndef()) 12750a17896fSGabor Marton return Visit(Sym); 12760a17896fSGabor Marton return Ret; 12770a17896fSGabor Marton } 12780a17896fSGabor Marton 127912294f8dSArtem Dergachev public: 128012294f8dSArtem Dergachev Simplifier(ProgramStateRef State) 128112294f8dSArtem Dergachev : State(State), SVB(State->getStateManager().getSValBuilder()) {} 128212294f8dSArtem Dergachev 128312294f8dSArtem Dergachev SVal VisitSymbolData(const SymbolData *S) { 12849fe9a95fSArtem Dergachev // No cache here. 128512294f8dSArtem Dergachev if (const llvm::APSInt *I = 1286*bc2c759aSGabor Marton State->getConstraintManager().getSymVal(State, S)) 128712294f8dSArtem Dergachev return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I) 128812294f8dSArtem Dergachev : (SVal)SVB.makeIntVal(*I); 128916a1f64cSArtem Dergachev return SVB.makeSymbolVal(S); 129012294f8dSArtem Dergachev } 129112294f8dSArtem Dergachev 129212294f8dSArtem Dergachev SVal VisitSymIntExpr(const SymIntExpr *S) { 129322746d7dSArtem Dergachev auto I = Cached.find(S); 129422746d7dSArtem Dergachev if (I != Cached.end()) 129522746d7dSArtem Dergachev return I->second; 129622746d7dSArtem Dergachev 12970a17896fSGabor Marton SVal LHS = getConstOrVisit(S->getLHS()); 12989fe9a95fSArtem Dergachev if (isUnchanged(S->getLHS(), LHS)) 12999fe9a95fSArtem Dergachev return skip(S); 13009fe9a95fSArtem Dergachev 130112294f8dSArtem Dergachev SVal RHS; 130212294f8dSArtem Dergachev // By looking at the APSInt in the right-hand side of S, we cannot 130312294f8dSArtem Dergachev // figure out if it should be treated as a Loc or as a NonLoc. 130412294f8dSArtem Dergachev // So make our guess by recalling that we cannot multiply pointers 130512294f8dSArtem Dergachev // or compare a pointer to an integer. 130612294f8dSArtem Dergachev if (Loc::isLocType(S->getLHS()->getType()) && 130712294f8dSArtem Dergachev BinaryOperator::isComparisonOp(S->getOpcode())) { 130812294f8dSArtem Dergachev // The usual conversion of $sym to &SymRegion{$sym}, as they have 130912294f8dSArtem Dergachev // the same meaning for Loc-type symbols, but the latter form 131012294f8dSArtem Dergachev // is preferred in SVal computations for being Loc itself. 131112294f8dSArtem Dergachev if (SymbolRef Sym = LHS.getAsSymbol()) { 131212294f8dSArtem Dergachev assert(Loc::isLocType(Sym->getType())); 131312294f8dSArtem Dergachev LHS = SVB.makeLoc(Sym); 131412294f8dSArtem Dergachev } 131512294f8dSArtem Dergachev RHS = SVB.makeIntLocVal(S->getRHS()); 131612294f8dSArtem Dergachev } else { 131712294f8dSArtem Dergachev RHS = SVB.makeIntVal(S->getRHS()); 131812294f8dSArtem Dergachev } 131922746d7dSArtem Dergachev 13209fe9a95fSArtem Dergachev return cache( 13219fe9a95fSArtem Dergachev S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType())); 132212294f8dSArtem Dergachev } 132312294f8dSArtem Dergachev 1324ffc32efdSGabor Marton SVal VisitIntSymExpr(const IntSymExpr *S) { 1325ffc32efdSGabor Marton auto I = Cached.find(S); 1326ffc32efdSGabor Marton if (I != Cached.end()) 1327ffc32efdSGabor Marton return I->second; 1328ffc32efdSGabor Marton 13290a17896fSGabor Marton SVal RHS = getConstOrVisit(S->getRHS()); 1330ffc32efdSGabor Marton if (isUnchanged(S->getRHS(), RHS)) 1331ffc32efdSGabor Marton return skip(S); 13320a17896fSGabor Marton 1333ffc32efdSGabor Marton SVal LHS = SVB.makeIntVal(S->getLHS()); 1334ffc32efdSGabor Marton return cache( 1335ffc32efdSGabor Marton S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType())); 1336ffc32efdSGabor Marton } 1337ffc32efdSGabor Marton 133812294f8dSArtem Dergachev SVal VisitSymSymExpr(const SymSymExpr *S) { 133922746d7dSArtem Dergachev auto I = Cached.find(S); 134022746d7dSArtem Dergachev if (I != Cached.end()) 134122746d7dSArtem Dergachev return I->second; 134222746d7dSArtem Dergachev 134305220a90SArtem Dergachev // For now don't try to simplify mixed Loc/NonLoc expressions 134405220a90SArtem Dergachev // because they often appear from LocAsInteger operations 134505220a90SArtem Dergachev // and we don't know how to combine a LocAsInteger 134605220a90SArtem Dergachev // with a concrete value. 134705220a90SArtem Dergachev if (Loc::isLocType(S->getLHS()->getType()) != 13489fe9a95fSArtem Dergachev Loc::isLocType(S->getRHS()->getType())) 13499fe9a95fSArtem Dergachev return skip(S); 135005220a90SArtem Dergachev 13510a17896fSGabor Marton SVal LHS = getConstOrVisit(S->getLHS()); 13520a17896fSGabor Marton SVal RHS = getConstOrVisit(S->getRHS()); 13530a17896fSGabor Marton 13549fe9a95fSArtem Dergachev if (isUnchanged(S->getLHS(), LHS) && isUnchanged(S->getRHS(), RHS)) 13559fe9a95fSArtem Dergachev return skip(S); 13569fe9a95fSArtem Dergachev 13579fe9a95fSArtem Dergachev return cache( 13589fe9a95fSArtem Dergachev S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType())); 135912294f8dSArtem Dergachev } 136012294f8dSArtem Dergachev 1361160798abSGabor Marton SVal VisitSymbolCast(const SymbolCast *S) { 1362160798abSGabor Marton auto I = Cached.find(S); 1363160798abSGabor Marton if (I != Cached.end()) 1364160798abSGabor Marton return I->second; 1365160798abSGabor Marton const SymExpr *OpSym = S->getOperand(); 1366160798abSGabor Marton SVal OpVal = getConstOrVisit(OpSym); 1367160798abSGabor Marton if (isUnchanged(OpSym, OpVal)) 1368160798abSGabor Marton return skip(S); 1369160798abSGabor Marton 1370160798abSGabor Marton return cache(S, SVB.evalCast(OpVal, S->getType(), OpSym->getType())); 1371160798abSGabor Marton } 1372b5b2aec1SGabor Marton 1373b5b2aec1SGabor Marton SVal VisitUnarySymExpr(const UnarySymExpr *S) { 1374b5b2aec1SGabor Marton auto I = Cached.find(S); 1375b5b2aec1SGabor Marton if (I != Cached.end()) 1376b5b2aec1SGabor Marton return I->second; 1377b5b2aec1SGabor Marton SVal Op = getConstOrVisit(S->getOperand()); 1378b5b2aec1SGabor Marton if (isUnchanged(S->getOperand(), Op)) 1379b5b2aec1SGabor Marton return skip(S); 1380b5b2aec1SGabor Marton 1381b5b2aec1SGabor Marton return cache( 1382b5b2aec1SGabor Marton S, SVB.evalUnaryOp(State, S->getOpcode(), Op, S->getType())); 1383b5b2aec1SGabor Marton } 1384b5b2aec1SGabor Marton 138512294f8dSArtem Dergachev SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); } 138612294f8dSArtem Dergachev 138712294f8dSArtem Dergachev SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); } 138812294f8dSArtem Dergachev 138912294f8dSArtem Dergachev SVal VisitNonLocSymbolVal(nonloc::SymbolVal V) { 139012294f8dSArtem Dergachev // Simplification is much more costly than computing complexity. 139112294f8dSArtem Dergachev // For high complexity, it may be not worth it. 139212294f8dSArtem Dergachev return Visit(V.getSymbol()); 139312294f8dSArtem Dergachev } 139412294f8dSArtem Dergachev 139512294f8dSArtem Dergachev SVal VisitSVal(SVal V) { return V; } 139612294f8dSArtem Dergachev }; 139712294f8dSArtem Dergachev 139816a1f64cSArtem Dergachev SVal SimplifiedV = Simplifier(State).Visit(V); 139916a1f64cSArtem Dergachev return SimplifiedV; 140012294f8dSArtem Dergachev } 1401