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" 142bbccca9SAdam Balogh #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 153a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h" 16d70ec366SAdam Balogh #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 17001fd5b4STed Kremenek #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 1812294f8dSArtem Dergachev #include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h" 19fa0734ecSArgyrios Kyrtzidis 20fa0734ecSArgyrios Kyrtzidis using namespace clang; 21fa0734ecSArgyrios Kyrtzidis using namespace ento; 22fa0734ecSArgyrios Kyrtzidis 23fa0734ecSArgyrios Kyrtzidis namespace { 24fa0734ecSArgyrios Kyrtzidis class SimpleSValBuilder : public SValBuilder { 25fa0734ecSArgyrios Kyrtzidis public: 26fa0734ecSArgyrios Kyrtzidis SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context, 27001fd5b4STed Kremenek ProgramStateManager &stateMgr) 28fa0734ecSArgyrios Kyrtzidis : SValBuilder(alloc, context, stateMgr) {} 29637d1e66SAngel Garcia Gomez ~SimpleSValBuilder() override {} 30fa0734ecSArgyrios Kyrtzidis 31fb6b25b5SCraig Topper SVal evalMinus(NonLoc val) override; 32fb6b25b5SCraig Topper SVal evalComplement(NonLoc val) override; 33fb6b25b5SCraig Topper SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op, 34fb6b25b5SCraig Topper NonLoc lhs, NonLoc rhs, QualType resultTy) override; 35fb6b25b5SCraig Topper SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op, 36fb6b25b5SCraig Topper Loc lhs, Loc rhs, QualType resultTy) override; 37fb6b25b5SCraig Topper SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op, 38fb6b25b5SCraig Topper Loc lhs, NonLoc rhs, QualType resultTy) override; 39fa0734ecSArgyrios Kyrtzidis 40fa0734ecSArgyrios Kyrtzidis /// getKnownValue - evaluates a given SVal. If the SVal has only one possible 41fa0734ecSArgyrios Kyrtzidis /// (integer) value, that value is returned. Otherwise, returns NULL. 42fb6b25b5SCraig Topper const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override; 43fa0734ecSArgyrios Kyrtzidis 4412294f8dSArtem Dergachev /// Recursively descends into symbolic expressions and replaces symbols 4512294f8dSArtem Dergachev /// with their known values (in the sense of the getKnownValue() method). 4612294f8dSArtem Dergachev SVal simplifySVal(ProgramStateRef State, SVal V) override; 4712294f8dSArtem Dergachev 48fa0734ecSArgyrios Kyrtzidis SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op, 49fa0734ecSArgyrios Kyrtzidis const llvm::APSInt &RHS, QualType resultTy); 50fa0734ecSArgyrios Kyrtzidis }; 51fa0734ecSArgyrios Kyrtzidis } // end anonymous namespace 52fa0734ecSArgyrios Kyrtzidis 53fa0734ecSArgyrios Kyrtzidis SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc, 54fa0734ecSArgyrios Kyrtzidis ASTContext &context, 55001fd5b4STed Kremenek ProgramStateManager &stateMgr) { 56fa0734ecSArgyrios Kyrtzidis return new SimpleSValBuilder(alloc, context, stateMgr); 57fa0734ecSArgyrios Kyrtzidis } 58fa0734ecSArgyrios Kyrtzidis 59fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===// 60fa0734ecSArgyrios Kyrtzidis // Transfer function for unary operators. 61fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===// 62fa0734ecSArgyrios Kyrtzidis 63fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::evalMinus(NonLoc val) { 64fa0734ecSArgyrios Kyrtzidis switch (val.getSubKind()) { 65fa0734ecSArgyrios Kyrtzidis case nonloc::ConcreteIntKind: 662fdacbc5SDavid Blaikie return val.castAs<nonloc::ConcreteInt>().evalMinus(*this); 67fa0734ecSArgyrios Kyrtzidis default: 68fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 69fa0734ecSArgyrios Kyrtzidis } 70fa0734ecSArgyrios Kyrtzidis } 71fa0734ecSArgyrios Kyrtzidis 72fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::evalComplement(NonLoc X) { 73fa0734ecSArgyrios Kyrtzidis switch (X.getSubKind()) { 74fa0734ecSArgyrios Kyrtzidis case nonloc::ConcreteIntKind: 752fdacbc5SDavid Blaikie return X.castAs<nonloc::ConcreteInt>().evalComplement(*this); 76fa0734ecSArgyrios Kyrtzidis default: 77fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 78fa0734ecSArgyrios Kyrtzidis } 79fa0734ecSArgyrios Kyrtzidis } 80fa0734ecSArgyrios Kyrtzidis 81fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===// 82fa0734ecSArgyrios Kyrtzidis // Transfer function for binary operators. 83fa0734ecSArgyrios Kyrtzidis //===----------------------------------------------------------------------===// 84fa0734ecSArgyrios Kyrtzidis 85fa0734ecSArgyrios Kyrtzidis SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS, 86fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode op, 87fa0734ecSArgyrios Kyrtzidis const llvm::APSInt &RHS, 88fa0734ecSArgyrios Kyrtzidis QualType resultTy) { 89fa0734ecSArgyrios Kyrtzidis bool isIdempotent = false; 90fa0734ecSArgyrios Kyrtzidis 91fa0734ecSArgyrios Kyrtzidis // Check for a few special cases with known reductions first. 92fa0734ecSArgyrios Kyrtzidis switch (op) { 93fa0734ecSArgyrios Kyrtzidis default: 94fa0734ecSArgyrios Kyrtzidis // We can't reduce this case; just treat it normally. 95fa0734ecSArgyrios Kyrtzidis break; 96fa0734ecSArgyrios Kyrtzidis case BO_Mul: 97fa0734ecSArgyrios Kyrtzidis // a*0 and a*1 98fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 99fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy); 100fa0734ecSArgyrios Kyrtzidis else if (RHS == 1) 101fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 102fa0734ecSArgyrios Kyrtzidis break; 103fa0734ecSArgyrios Kyrtzidis case BO_Div: 104fa0734ecSArgyrios Kyrtzidis // a/0 and a/1 105fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 106fa0734ecSArgyrios Kyrtzidis // This is also handled elsewhere. 107fa0734ecSArgyrios Kyrtzidis return UndefinedVal(); 108fa0734ecSArgyrios Kyrtzidis else if (RHS == 1) 109fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 110fa0734ecSArgyrios Kyrtzidis break; 111fa0734ecSArgyrios Kyrtzidis case BO_Rem: 112fa0734ecSArgyrios Kyrtzidis // a%0 and a%1 113fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 114fa0734ecSArgyrios Kyrtzidis // This is also handled elsewhere. 115fa0734ecSArgyrios Kyrtzidis return UndefinedVal(); 116fa0734ecSArgyrios Kyrtzidis else if (RHS == 1) 117fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy); 118fa0734ecSArgyrios Kyrtzidis break; 119fa0734ecSArgyrios Kyrtzidis case BO_Add: 120fa0734ecSArgyrios Kyrtzidis case BO_Sub: 121fa0734ecSArgyrios Kyrtzidis case BO_Shl: 122fa0734ecSArgyrios Kyrtzidis case BO_Shr: 123fa0734ecSArgyrios Kyrtzidis case BO_Xor: 124fa0734ecSArgyrios Kyrtzidis // a+0, a-0, a<<0, a>>0, a^0 125fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 126fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 127fa0734ecSArgyrios Kyrtzidis break; 128fa0734ecSArgyrios Kyrtzidis case BO_And: 129fa0734ecSArgyrios Kyrtzidis // a&0 and a&(~0) 130fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 131fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy); 132fa0734ecSArgyrios Kyrtzidis else if (RHS.isAllOnesValue()) 133fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 134fa0734ecSArgyrios Kyrtzidis break; 135fa0734ecSArgyrios Kyrtzidis case BO_Or: 136fa0734ecSArgyrios Kyrtzidis // a|0 and a|(~0) 137fa0734ecSArgyrios Kyrtzidis if (RHS == 0) 138fa0734ecSArgyrios Kyrtzidis isIdempotent = true; 139fa0734ecSArgyrios Kyrtzidis else if (RHS.isAllOnesValue()) { 140fa0734ecSArgyrios Kyrtzidis const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS); 141fa0734ecSArgyrios Kyrtzidis return nonloc::ConcreteInt(Result); 142fa0734ecSArgyrios Kyrtzidis } 143fa0734ecSArgyrios Kyrtzidis break; 144fa0734ecSArgyrios Kyrtzidis } 145fa0734ecSArgyrios Kyrtzidis 146fa0734ecSArgyrios Kyrtzidis // Idempotent ops (like a*1) can still change the type of an expression. 147*01ddfa95SDenys Petrov // Wrap the LHS up in a NonLoc again and let evalCast do the 1485ad574c0SZhanyong Wan // dirty work. 149d066f79cSAnna Zaks if (isIdempotent) 150*01ddfa95SDenys Petrov return evalCast(nonloc::SymbolVal(LHS), resultTy, QualType{}); 151fa0734ecSArgyrios Kyrtzidis 152fa0734ecSArgyrios Kyrtzidis // If we reach this point, the expression cannot be simplified. 15354569448SJordy Rose // Make a SymbolVal for the entire expression, after converting the RHS. 15454569448SJordy Rose const llvm::APSInt *ConvertedRHS = &RHS; 15554569448SJordy Rose if (BinaryOperator::isComparisonOp(op)) { 15654569448SJordy Rose // We're looking for a type big enough to compare the symbolic value 15754569448SJordy Rose // with the given constant. 15854569448SJordy Rose // FIXME: This is an approximation of Sema::UsualArithmeticConversions. 15954569448SJordy Rose ASTContext &Ctx = getContext(); 160a808e165STed Kremenek QualType SymbolType = LHS->getType(); 16154569448SJordy Rose uint64_t ValWidth = RHS.getBitWidth(); 16254569448SJordy Rose uint64_t TypeWidth = Ctx.getTypeSize(SymbolType); 16354569448SJordy Rose 16454569448SJordy Rose if (ValWidth < TypeWidth) { 16554569448SJordy Rose // If the value is too small, extend it. 16654569448SJordy Rose ConvertedRHS = &BasicVals.Convert(SymbolType, RHS); 16754569448SJordy Rose } else if (ValWidth == TypeWidth) { 16854569448SJordy Rose // If the value is signed but the symbol is unsigned, do the comparison 16954569448SJordy Rose // in unsigned space. [C99 6.3.1.8] 17054569448SJordy Rose // (For the opposite case, the value is already unsigned.) 17154569448SJordy Rose if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType()) 17254569448SJordy Rose ConvertedRHS = &BasicVals.Convert(SymbolType, RHS); 17354569448SJordy Rose } 17454569448SJordy Rose } else 17554569448SJordy Rose ConvertedRHS = &BasicVals.Convert(resultTy, RHS); 17654569448SJordy Rose 17754569448SJordy Rose return makeNonLoc(LHS, op, *ConvertedRHS, resultTy); 178fa0734ecSArgyrios Kyrtzidis } 179fa0734ecSArgyrios Kyrtzidis 1802bbccca9SAdam Balogh // See if Sym is known to be a relation Rel with Bound. 1812bbccca9SAdam Balogh static bool isInRelation(BinaryOperator::Opcode Rel, SymbolRef Sym, 1822bbccca9SAdam Balogh llvm::APSInt Bound, ProgramStateRef State) { 1832bbccca9SAdam Balogh SValBuilder &SVB = State->getStateManager().getSValBuilder(); 1842bbccca9SAdam Balogh SVal Result = 1852bbccca9SAdam Balogh SVB.evalBinOpNN(State, Rel, nonloc::SymbolVal(Sym), 1862bbccca9SAdam Balogh nonloc::ConcreteInt(Bound), SVB.getConditionType()); 1872bbccca9SAdam Balogh if (auto DV = Result.getAs<DefinedSVal>()) { 1882bbccca9SAdam Balogh return !State->assume(*DV, false); 1892bbccca9SAdam Balogh } 1902bbccca9SAdam Balogh return false; 1912bbccca9SAdam Balogh } 1922bbccca9SAdam Balogh 1932bbccca9SAdam Balogh // See if Sym is known to be within [min/4, max/4], where min and max 1942bbccca9SAdam Balogh // are the bounds of the symbol's integral type. With such symbols, 1952bbccca9SAdam Balogh // some manipulations can be performed without the risk of overflow. 1962bbccca9SAdam Balogh // assume() doesn't cause infinite recursion because we should be dealing 1972bbccca9SAdam Balogh // with simpler symbols on every recursive call. 1982bbccca9SAdam Balogh static bool isWithinConstantOverflowBounds(SymbolRef Sym, 1992bbccca9SAdam Balogh ProgramStateRef State) { 2002bbccca9SAdam Balogh SValBuilder &SVB = State->getStateManager().getSValBuilder(); 2012bbccca9SAdam Balogh BasicValueFactory &BV = SVB.getBasicValueFactory(); 2022bbccca9SAdam Balogh 2032bbccca9SAdam Balogh QualType T = Sym->getType(); 2042bbccca9SAdam Balogh assert(T->isSignedIntegerOrEnumerationType() && 2052bbccca9SAdam Balogh "This only works with signed integers!"); 2062bbccca9SAdam Balogh APSIntType AT = BV.getAPSIntType(T); 2072bbccca9SAdam Balogh 2082bbccca9SAdam Balogh llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max; 2092bbccca9SAdam Balogh return isInRelation(BO_LE, Sym, Max, State) && 2102bbccca9SAdam Balogh isInRelation(BO_GE, Sym, Min, State); 2112bbccca9SAdam Balogh } 2122bbccca9SAdam Balogh 2132bbccca9SAdam Balogh // Same for the concrete integers: see if I is within [min/4, max/4]. 2142bbccca9SAdam Balogh static bool isWithinConstantOverflowBounds(llvm::APSInt I) { 2152bbccca9SAdam Balogh APSIntType AT(I); 2162bbccca9SAdam Balogh assert(!AT.isUnsigned() && 2172bbccca9SAdam Balogh "This only works with signed integers!"); 2182bbccca9SAdam Balogh 2192bbccca9SAdam Balogh llvm::APSInt Max = AT.getMaxValue() / AT.getValue(4), Min = -Max; 2202bbccca9SAdam Balogh return (I <= Max) && (I >= -Max); 2212bbccca9SAdam Balogh } 2222bbccca9SAdam Balogh 2232bbccca9SAdam Balogh static std::pair<SymbolRef, llvm::APSInt> 2242bbccca9SAdam Balogh decomposeSymbol(SymbolRef Sym, BasicValueFactory &BV) { 2252bbccca9SAdam Balogh if (const auto *SymInt = dyn_cast<SymIntExpr>(Sym)) 2262bbccca9SAdam Balogh if (BinaryOperator::isAdditiveOp(SymInt->getOpcode())) 2272bbccca9SAdam Balogh return std::make_pair(SymInt->getLHS(), 2282bbccca9SAdam Balogh (SymInt->getOpcode() == BO_Add) ? 2292bbccca9SAdam Balogh (SymInt->getRHS()) : 2302bbccca9SAdam Balogh (-SymInt->getRHS())); 2312bbccca9SAdam Balogh 2322bbccca9SAdam Balogh // Fail to decompose: "reduce" the problem to the "$x + 0" case. 2332bbccca9SAdam Balogh return std::make_pair(Sym, BV.getValue(0, Sym->getType())); 2342bbccca9SAdam Balogh } 2352bbccca9SAdam Balogh 2362bbccca9SAdam Balogh // Simplify "(LSym + LInt) Op (RSym + RInt)" assuming all values are of the 2372bbccca9SAdam Balogh // same signed integral type and no overflows occur (which should be checked 2382bbccca9SAdam Balogh // by the caller). 2392bbccca9SAdam Balogh static NonLoc doRearrangeUnchecked(ProgramStateRef State, 2402bbccca9SAdam Balogh BinaryOperator::Opcode Op, 2412bbccca9SAdam Balogh SymbolRef LSym, llvm::APSInt LInt, 2422bbccca9SAdam Balogh SymbolRef RSym, llvm::APSInt RInt) { 2432bbccca9SAdam Balogh SValBuilder &SVB = State->getStateManager().getSValBuilder(); 2442bbccca9SAdam Balogh BasicValueFactory &BV = SVB.getBasicValueFactory(); 2452bbccca9SAdam Balogh SymbolManager &SymMgr = SVB.getSymbolManager(); 2462bbccca9SAdam Balogh 2472bbccca9SAdam Balogh QualType SymTy = LSym->getType(); 2482bbccca9SAdam Balogh assert(SymTy == RSym->getType() && 2492bbccca9SAdam Balogh "Symbols are not of the same type!"); 2502bbccca9SAdam Balogh assert(APSIntType(LInt) == BV.getAPSIntType(SymTy) && 2512bbccca9SAdam Balogh "Integers are not of the same type as symbols!"); 2522bbccca9SAdam Balogh assert(APSIntType(RInt) == BV.getAPSIntType(SymTy) && 2532bbccca9SAdam Balogh "Integers are not of the same type as symbols!"); 2542bbccca9SAdam Balogh 2552bbccca9SAdam Balogh QualType ResultTy; 2562bbccca9SAdam Balogh if (BinaryOperator::isComparisonOp(Op)) 2572bbccca9SAdam Balogh ResultTy = SVB.getConditionType(); 2582bbccca9SAdam Balogh else if (BinaryOperator::isAdditiveOp(Op)) 2592bbccca9SAdam Balogh ResultTy = SymTy; 2602bbccca9SAdam Balogh else 2612bbccca9SAdam Balogh llvm_unreachable("Operation not suitable for unchecked rearrangement!"); 2622bbccca9SAdam Balogh 2632bbccca9SAdam Balogh // FIXME: Can we use assume() without getting into an infinite recursion? 2642bbccca9SAdam Balogh if (LSym == RSym) 2652bbccca9SAdam Balogh return SVB.evalBinOpNN(State, Op, nonloc::ConcreteInt(LInt), 2662bbccca9SAdam Balogh nonloc::ConcreteInt(RInt), ResultTy) 2672bbccca9SAdam Balogh .castAs<NonLoc>(); 2682bbccca9SAdam Balogh 2692bbccca9SAdam Balogh SymbolRef ResultSym = nullptr; 2702bbccca9SAdam Balogh BinaryOperator::Opcode ResultOp; 2712bbccca9SAdam Balogh llvm::APSInt ResultInt; 2722bbccca9SAdam Balogh if (BinaryOperator::isComparisonOp(Op)) { 2732bbccca9SAdam Balogh // Prefer comparing to a non-negative number. 2742bbccca9SAdam Balogh // FIXME: Maybe it'd be better to have consistency in 2752bbccca9SAdam Balogh // "$x - $y" vs. "$y - $x" because those are solver's keys. 2762bbccca9SAdam Balogh if (LInt > RInt) { 2772bbccca9SAdam Balogh ResultSym = SymMgr.getSymSymExpr(RSym, BO_Sub, LSym, SymTy); 2782bbccca9SAdam Balogh ResultOp = BinaryOperator::reverseComparisonOp(Op); 2792bbccca9SAdam Balogh ResultInt = LInt - RInt; // Opposite order! 2802bbccca9SAdam Balogh } else { 2812bbccca9SAdam Balogh ResultSym = SymMgr.getSymSymExpr(LSym, BO_Sub, RSym, SymTy); 2822bbccca9SAdam Balogh ResultOp = Op; 2832bbccca9SAdam Balogh ResultInt = RInt - LInt; // Opposite order! 2842bbccca9SAdam Balogh } 2852bbccca9SAdam Balogh } else { 2862bbccca9SAdam Balogh ResultSym = SymMgr.getSymSymExpr(LSym, Op, RSym, SymTy); 2872bbccca9SAdam Balogh ResultInt = (Op == BO_Add) ? (LInt + RInt) : (LInt - RInt); 2882bbccca9SAdam Balogh ResultOp = BO_Add; 2892bbccca9SAdam Balogh // Bring back the cosmetic difference. 2902bbccca9SAdam Balogh if (ResultInt < 0) { 2912bbccca9SAdam Balogh ResultInt = -ResultInt; 2922bbccca9SAdam Balogh ResultOp = BO_Sub; 2932bbccca9SAdam Balogh } else if (ResultInt == 0) { 2942bbccca9SAdam Balogh // Shortcut: Simplify "$x + 0" to "$x". 2952bbccca9SAdam Balogh return nonloc::SymbolVal(ResultSym); 2962bbccca9SAdam Balogh } 2972bbccca9SAdam Balogh } 2982bbccca9SAdam Balogh const llvm::APSInt &PersistentResultInt = BV.getValue(ResultInt); 2992bbccca9SAdam Balogh return nonloc::SymbolVal( 3002bbccca9SAdam Balogh SymMgr.getSymIntExpr(ResultSym, ResultOp, PersistentResultInt, ResultTy)); 3012bbccca9SAdam Balogh } 3022bbccca9SAdam Balogh 3032bbccca9SAdam Balogh // Rearrange if symbol type matches the result type and if the operator is a 3042bbccca9SAdam Balogh // comparison operator, both symbol and constant must be within constant 3052bbccca9SAdam Balogh // overflow bounds. 3062bbccca9SAdam Balogh static bool shouldRearrange(ProgramStateRef State, BinaryOperator::Opcode Op, 3072bbccca9SAdam Balogh SymbolRef Sym, llvm::APSInt Int, QualType Ty) { 3082bbccca9SAdam Balogh return Sym->getType() == Ty && 3092bbccca9SAdam Balogh (!BinaryOperator::isComparisonOp(Op) || 3102bbccca9SAdam Balogh (isWithinConstantOverflowBounds(Sym, State) && 3112bbccca9SAdam Balogh isWithinConstantOverflowBounds(Int))); 3122bbccca9SAdam Balogh } 3132bbccca9SAdam Balogh 3142bbccca9SAdam Balogh static Optional<NonLoc> tryRearrange(ProgramStateRef State, 3152bbccca9SAdam Balogh BinaryOperator::Opcode Op, NonLoc Lhs, 3162bbccca9SAdam Balogh NonLoc Rhs, QualType ResultTy) { 3172bbccca9SAdam Balogh ProgramStateManager &StateMgr = State->getStateManager(); 3182bbccca9SAdam Balogh SValBuilder &SVB = StateMgr.getSValBuilder(); 3192bbccca9SAdam Balogh 3202bbccca9SAdam Balogh // We expect everything to be of the same type - this type. 3212bbccca9SAdam Balogh QualType SingleTy; 3222bbccca9SAdam Balogh 3232bbccca9SAdam Balogh auto &Opts = 32421aa8db6SGabor Horvath StateMgr.getOwningEngine().getAnalysisManager().getAnalyzerOptions(); 3252bbccca9SAdam Balogh 326dcde8accSAdam Balogh // FIXME: After putting complexity threshold to the symbols we can always 327dcde8accSAdam Balogh // rearrange additive operations but rearrange comparisons only if 328dcde8accSAdam Balogh // option is set. 329549f9cd4SKristof Umann if(!Opts.ShouldAggressivelySimplifyBinaryOperation) 330dcde8accSAdam Balogh return None; 331dcde8accSAdam Balogh 3322bbccca9SAdam Balogh SymbolRef LSym = Lhs.getAsSymbol(); 3332bbccca9SAdam Balogh if (!LSym) 3342bbccca9SAdam Balogh return None; 3352bbccca9SAdam Balogh 336dcde8accSAdam Balogh if (BinaryOperator::isComparisonOp(Op)) { 3372bbccca9SAdam Balogh SingleTy = LSym->getType(); 3382bbccca9SAdam Balogh if (ResultTy != SVB.getConditionType()) 3392bbccca9SAdam Balogh return None; 3402bbccca9SAdam Balogh // Initialize SingleTy later with a symbol's type. 3412bbccca9SAdam Balogh } else if (BinaryOperator::isAdditiveOp(Op)) { 3422bbccca9SAdam Balogh SingleTy = ResultTy; 34313e186c0SAdam Balogh if (LSym->getType() != SingleTy) 34413e186c0SAdam Balogh return None; 3452bbccca9SAdam Balogh } else { 3462bbccca9SAdam Balogh // Don't rearrange other operations. 3472bbccca9SAdam Balogh return None; 3482bbccca9SAdam Balogh } 3492bbccca9SAdam Balogh 3502bbccca9SAdam Balogh assert(!SingleTy.isNull() && "We should have figured out the type by now!"); 3512bbccca9SAdam Balogh 352471d0864SAdam Balogh // Rearrange signed symbolic expressions only 353471d0864SAdam Balogh if (!SingleTy->isSignedIntegerOrEnumerationType()) 354471d0864SAdam Balogh return None; 355471d0864SAdam Balogh 3562bbccca9SAdam Balogh SymbolRef RSym = Rhs.getAsSymbol(); 3572bbccca9SAdam Balogh if (!RSym || RSym->getType() != SingleTy) 3582bbccca9SAdam Balogh return None; 3592bbccca9SAdam Balogh 3602bbccca9SAdam Balogh BasicValueFactory &BV = State->getBasicVals(); 3612bbccca9SAdam Balogh llvm::APSInt LInt, RInt; 3622bbccca9SAdam Balogh std::tie(LSym, LInt) = decomposeSymbol(LSym, BV); 3632bbccca9SAdam Balogh std::tie(RSym, RInt) = decomposeSymbol(RSym, BV); 3642bbccca9SAdam Balogh if (!shouldRearrange(State, Op, LSym, LInt, SingleTy) || 3652bbccca9SAdam Balogh !shouldRearrange(State, Op, RSym, RInt, SingleTy)) 3662bbccca9SAdam Balogh return None; 3672bbccca9SAdam Balogh 3682bbccca9SAdam Balogh // We know that no overflows can occur anymore. 3692bbccca9SAdam Balogh return doRearrangeUnchecked(State, Op, LSym, LInt, RSym, RInt); 3702bbccca9SAdam Balogh } 3712bbccca9SAdam Balogh 37249b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state, 373fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode op, 374fa0734ecSArgyrios Kyrtzidis NonLoc lhs, NonLoc rhs, 375fa0734ecSArgyrios Kyrtzidis QualType resultTy) { 376f0e9ca86SAnna Zaks NonLoc InputLHS = lhs; 377f0e9ca86SAnna Zaks NonLoc InputRHS = rhs; 378f0e9ca86SAnna Zaks 379fa0734ecSArgyrios Kyrtzidis // Handle trivial case where left-side and right-side are the same. 380fa0734ecSArgyrios Kyrtzidis if (lhs == rhs) 381fa0734ecSArgyrios Kyrtzidis switch (op) { 382fa0734ecSArgyrios Kyrtzidis default: 383fa0734ecSArgyrios Kyrtzidis break; 384fa0734ecSArgyrios Kyrtzidis case BO_EQ: 385fa0734ecSArgyrios Kyrtzidis case BO_LE: 386fa0734ecSArgyrios Kyrtzidis case BO_GE: 387fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 388fa0734ecSArgyrios Kyrtzidis case BO_LT: 389fa0734ecSArgyrios Kyrtzidis case BO_GT: 390fa0734ecSArgyrios Kyrtzidis case BO_NE: 391fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 392fa0734ecSArgyrios Kyrtzidis case BO_Xor: 393fa0734ecSArgyrios Kyrtzidis case BO_Sub: 3947523d1a8SJordan Rose if (resultTy->isIntegralOrEnumerationType()) 395fa0734ecSArgyrios Kyrtzidis return makeIntVal(0, resultTy); 396*01ddfa95SDenys Petrov return evalCast(makeIntVal(0, /*isUnsigned=*/false), resultTy, 397*01ddfa95SDenys Petrov QualType{}); 398fa0734ecSArgyrios Kyrtzidis case BO_Or: 399fa0734ecSArgyrios Kyrtzidis case BO_And: 400*01ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 401fa0734ecSArgyrios Kyrtzidis } 402fa0734ecSArgyrios Kyrtzidis 403fa0734ecSArgyrios Kyrtzidis while (1) { 404fa0734ecSArgyrios Kyrtzidis switch (lhs.getSubKind()) { 405fa0734ecSArgyrios Kyrtzidis default: 406bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, lhs, rhs, resultTy); 40764c01f7bSDevin Coughlin case nonloc::PointerToMemberKind: { 40864c01f7bSDevin Coughlin assert(rhs.getSubKind() == nonloc::PointerToMemberKind && 40964c01f7bSDevin Coughlin "Both SVals should have pointer-to-member-type"); 41064c01f7bSDevin Coughlin auto LPTM = lhs.castAs<nonloc::PointerToMember>(), 41164c01f7bSDevin Coughlin RPTM = rhs.castAs<nonloc::PointerToMember>(); 41264c01f7bSDevin Coughlin auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData(); 41364c01f7bSDevin Coughlin switch (op) { 41464c01f7bSDevin Coughlin case BO_EQ: 41564c01f7bSDevin Coughlin return makeTruthVal(LPTMD == RPTMD, resultTy); 41664c01f7bSDevin Coughlin case BO_NE: 41764c01f7bSDevin Coughlin return makeTruthVal(LPTMD != RPTMD, resultTy); 41864c01f7bSDevin Coughlin default: 41964c01f7bSDevin Coughlin return UnknownVal(); 42064c01f7bSDevin Coughlin } 42164c01f7bSDevin Coughlin } 422fa0734ecSArgyrios Kyrtzidis case nonloc::LocAsIntegerKind: { 4232fdacbc5SDavid Blaikie Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc(); 424fa0734ecSArgyrios Kyrtzidis switch (rhs.getSubKind()) { 425fa0734ecSArgyrios Kyrtzidis case nonloc::LocAsIntegerKind: 42618d77984SAlexander Shaposhnikov // FIXME: at the moment the implementation 42718d77984SAlexander Shaposhnikov // of modeling "pointers as integers" is not complete. 42818d77984SAlexander Shaposhnikov if (!BinaryOperator::isComparisonOp(op)) 42918d77984SAlexander Shaposhnikov return UnknownVal(); 430fa0734ecSArgyrios Kyrtzidis return evalBinOpLL(state, op, lhsL, 4312fdacbc5SDavid Blaikie rhs.castAs<nonloc::LocAsInteger>().getLoc(), 432fa0734ecSArgyrios Kyrtzidis resultTy); 433fa0734ecSArgyrios Kyrtzidis case nonloc::ConcreteIntKind: { 43418d77984SAlexander Shaposhnikov // FIXME: at the moment the implementation 43518d77984SAlexander Shaposhnikov // of modeling "pointers as integers" is not complete. 43618d77984SAlexander Shaposhnikov if (!BinaryOperator::isComparisonOp(op)) 43718d77984SAlexander Shaposhnikov return UnknownVal(); 438fa0734ecSArgyrios Kyrtzidis // Transform the integer into a location and compare. 4397333a9eaSArtem Dergachev // FIXME: This only makes sense for comparisons. If we want to, say, 4407333a9eaSArtem Dergachev // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it, 4417333a9eaSArtem Dergachev // then pack it back into a LocAsInteger. 4422fdacbc5SDavid Blaikie llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue(); 44327ed855aSDavid Stenberg // If the region has a symbolic base, pay attention to the type; it 44427ed855aSDavid Stenberg // might be coming from a non-default address space. For non-symbolic 44527ed855aSDavid Stenberg // regions it doesn't matter that much because such comparisons would 44627ed855aSDavid Stenberg // most likely evaluate to concrete false anyway. FIXME: We might 44727ed855aSDavid Stenberg // still need to handle the non-comparison case. 44827ed855aSDavid Stenberg if (SymbolRef lSym = lhs.getAsLocSymbol(true)) 44927ed855aSDavid Stenberg BasicVals.getAPSIntType(lSym->getType()).apply(i); 45027ed855aSDavid Stenberg else 4517e3c3ea3SJordy Rose BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i); 452fa0734ecSArgyrios Kyrtzidis return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy); 453fa0734ecSArgyrios Kyrtzidis } 454fa0734ecSArgyrios Kyrtzidis default: 455fa0734ecSArgyrios Kyrtzidis switch (op) { 456fa0734ecSArgyrios Kyrtzidis case BO_EQ: 457fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 458fa0734ecSArgyrios Kyrtzidis case BO_NE: 459fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 460fa0734ecSArgyrios Kyrtzidis default: 461fa0734ecSArgyrios Kyrtzidis // This case also handles pointer arithmetic. 462bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy); 463fa0734ecSArgyrios Kyrtzidis } 464fa0734ecSArgyrios Kyrtzidis } 465fa0734ecSArgyrios Kyrtzidis } 466d066f79cSAnna Zaks case nonloc::ConcreteIntKind: { 4672fdacbc5SDavid Blaikie llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue(); 468d066f79cSAnna Zaks 46954569448SJordy Rose // If we're dealing with two known constants, just perform the operation. 47054569448SJordy Rose if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) { 47154569448SJordy Rose llvm::APSInt RHSValue = *KnownRHSValue; 47254569448SJordy Rose if (BinaryOperator::isComparisonOp(op)) { 47354569448SJordy Rose // We're looking for a type big enough to compare the two values. 4747e3c3ea3SJordy Rose // FIXME: This is not correct. char + short will result in a promotion 4757e3c3ea3SJordy Rose // to int. Unfortunately we have lost types by this point. 4767e3c3ea3SJordy Rose APSIntType CompareType = std::max(APSIntType(LHSValue), 4777e3c3ea3SJordy Rose APSIntType(RHSValue)); 4787e3c3ea3SJordy Rose CompareType.apply(LHSValue); 4797e3c3ea3SJordy Rose CompareType.apply(RHSValue); 48054569448SJordy Rose } else if (!BinaryOperator::isShiftOp(op)) { 4817e3c3ea3SJordy Rose APSIntType IntType = BasicVals.getAPSIntType(resultTy); 4827e3c3ea3SJordy Rose IntType.apply(LHSValue); 4837e3c3ea3SJordy Rose IntType.apply(RHSValue); 484d066f79cSAnna Zaks } 485d066f79cSAnna Zaks 48654569448SJordy Rose const llvm::APSInt *Result = 48754569448SJordy Rose BasicVals.evalAPSInt(op, LHSValue, RHSValue); 48854569448SJordy Rose if (!Result) 48954569448SJordy Rose return UndefinedVal(); 49054569448SJordy Rose 49154569448SJordy Rose return nonloc::ConcreteInt(*Result); 49254569448SJordy Rose } 493d066f79cSAnna Zaks 494d066f79cSAnna Zaks // Swap the left and right sides and flip the operator if doing so 495d066f79cSAnna Zaks // allows us to better reason about the expression (this is a form 496d066f79cSAnna Zaks // of expression canonicalization). 497d066f79cSAnna Zaks // While we're at it, catch some special cases for non-commutative ops. 498d066f79cSAnna Zaks switch (op) { 499d066f79cSAnna Zaks case BO_LT: 500d066f79cSAnna Zaks case BO_GT: 501d066f79cSAnna Zaks case BO_LE: 502d066f79cSAnna Zaks case BO_GE: 503604d0bbbSJordan Rose op = BinaryOperator::reverseComparisonOp(op); 5044dc0b1acSReid Kleckner LLVM_FALLTHROUGH; 505d066f79cSAnna Zaks case BO_EQ: 506d066f79cSAnna Zaks case BO_NE: 507d066f79cSAnna Zaks case BO_Add: 508d066f79cSAnna Zaks case BO_Mul: 509d066f79cSAnna Zaks case BO_And: 510d066f79cSAnna Zaks case BO_Xor: 511d066f79cSAnna Zaks case BO_Or: 51254569448SJordy Rose std::swap(lhs, rhs); 513d066f79cSAnna Zaks continue; 514d066f79cSAnna Zaks case BO_Shr: 51554569448SJordy Rose // (~0)>>a 51654569448SJordy Rose if (LHSValue.isAllOnesValue() && LHSValue.isSigned()) 517*01ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 5184dc0b1acSReid Kleckner LLVM_FALLTHROUGH; 519d066f79cSAnna Zaks case BO_Shl: 52054569448SJordy Rose // 0<<a and 0>>a 52154569448SJordy Rose if (LHSValue == 0) 522*01ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 523bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy); 524015c3988SGabor Marton case BO_Div: 525015c3988SGabor Marton // 0 / x == 0 52673c120a9SValeriy Savchenko case BO_Rem: 52773c120a9SValeriy Savchenko // 0 % x == 0 52873c120a9SValeriy Savchenko if (LHSValue == 0) 52973c120a9SValeriy Savchenko return makeZeroVal(resultTy); 53073c120a9SValeriy Savchenko LLVM_FALLTHROUGH; 531d066f79cSAnna Zaks default: 532bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy); 533d066f79cSAnna Zaks } 534d066f79cSAnna Zaks } 535d066f79cSAnna Zaks case nonloc::SymbolValKind: { 53654569448SJordy Rose // We only handle LHS as simple symbols or SymIntExprs. 5372fdacbc5SDavid Blaikie SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol(); 538d066f79cSAnna Zaks 539d066f79cSAnna Zaks // LHS is a symbolic expression. 54054569448SJordy Rose if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) { 541fa0734ecSArgyrios Kyrtzidis 542fa0734ecSArgyrios Kyrtzidis // Is this a logical not? (!x is represented as x == 0.) 543fa0734ecSArgyrios Kyrtzidis if (op == BO_EQ && rhs.isZeroConstant()) { 544fa0734ecSArgyrios Kyrtzidis // We know how to negate certain expressions. Simplify them here. 545fa0734ecSArgyrios Kyrtzidis 546fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode opc = symIntExpr->getOpcode(); 547fa0734ecSArgyrios Kyrtzidis switch (opc) { 548fa0734ecSArgyrios Kyrtzidis default: 549fa0734ecSArgyrios Kyrtzidis // We don't know how to negate this operation. 550fa0734ecSArgyrios Kyrtzidis // Just handle it as if it were a normal comparison to 0. 551fa0734ecSArgyrios Kyrtzidis break; 552fa0734ecSArgyrios Kyrtzidis case BO_LAnd: 553fa0734ecSArgyrios Kyrtzidis case BO_LOr: 55483d382b1SDavid Blaikie llvm_unreachable("Logical operators handled by branching logic."); 555fa0734ecSArgyrios Kyrtzidis case BO_Assign: 556fa0734ecSArgyrios Kyrtzidis case BO_MulAssign: 557fa0734ecSArgyrios Kyrtzidis case BO_DivAssign: 558fa0734ecSArgyrios Kyrtzidis case BO_RemAssign: 559fa0734ecSArgyrios Kyrtzidis case BO_AddAssign: 560fa0734ecSArgyrios Kyrtzidis case BO_SubAssign: 561fa0734ecSArgyrios Kyrtzidis case BO_ShlAssign: 562fa0734ecSArgyrios Kyrtzidis case BO_ShrAssign: 563fa0734ecSArgyrios Kyrtzidis case BO_AndAssign: 564fa0734ecSArgyrios Kyrtzidis case BO_XorAssign: 565fa0734ecSArgyrios Kyrtzidis case BO_OrAssign: 566fa0734ecSArgyrios Kyrtzidis case BO_Comma: 56783d382b1SDavid Blaikie llvm_unreachable("'=' and ',' operators handled by ExprEngine."); 568fa0734ecSArgyrios Kyrtzidis case BO_PtrMemD: 569fa0734ecSArgyrios Kyrtzidis case BO_PtrMemI: 57083d382b1SDavid Blaikie llvm_unreachable("Pointer arithmetic not handled here."); 571fa0734ecSArgyrios Kyrtzidis case BO_LT: 572fa0734ecSArgyrios Kyrtzidis case BO_GT: 573fa0734ecSArgyrios Kyrtzidis case BO_LE: 574fa0734ecSArgyrios Kyrtzidis case BO_GE: 575fa0734ecSArgyrios Kyrtzidis case BO_EQ: 576fa0734ecSArgyrios Kyrtzidis case BO_NE: 577dc16628cSJordan Rose assert(resultTy->isBooleanType() || 578dc16628cSJordan Rose resultTy == getConditionType()); 579dc16628cSJordan Rose assert(symIntExpr->getType()->isBooleanType() || 580dc16628cSJordan Rose getContext().hasSameUnqualifiedType(symIntExpr->getType(), 581dc16628cSJordan Rose getConditionType())); 582fa0734ecSArgyrios Kyrtzidis // Negate the comparison and make a value. 583604d0bbbSJordan Rose opc = BinaryOperator::negateComparisonOp(opc); 584fa0734ecSArgyrios Kyrtzidis return makeNonLoc(symIntExpr->getLHS(), opc, 585fa0734ecSArgyrios Kyrtzidis symIntExpr->getRHS(), resultTy); 586fa0734ecSArgyrios Kyrtzidis } 587fa0734ecSArgyrios Kyrtzidis } 588fa0734ecSArgyrios Kyrtzidis 589fa0734ecSArgyrios Kyrtzidis // For now, only handle expressions whose RHS is a constant. 59054569448SJordy Rose if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) { 591fa0734ecSArgyrios Kyrtzidis // If both the LHS and the current expression are additive, 59254569448SJordy Rose // fold their constants and try again. 593fa0734ecSArgyrios Kyrtzidis if (BinaryOperator::isAdditiveOp(op)) { 594fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode lop = symIntExpr->getOpcode(); 595fa0734ecSArgyrios Kyrtzidis if (BinaryOperator::isAdditiveOp(lop)) { 59654569448SJordy Rose // Convert the two constants to a common type, then combine them. 59754569448SJordy Rose 598fa0734ecSArgyrios Kyrtzidis // resultTy may not be the best type to convert to, but it's 599fa0734ecSArgyrios Kyrtzidis // probably the best choice in expressions with mixed type 600fa0734ecSArgyrios Kyrtzidis // (such as x+1U+2LL). The rules for implicit conversions should 601fa0734ecSArgyrios Kyrtzidis // choose a reasonable type to preserve the expression, and will 602fa0734ecSArgyrios Kyrtzidis // at least match how the value is going to be used. 6037e3c3ea3SJordy Rose APSIntType IntType = BasicVals.getAPSIntType(resultTy); 6047e3c3ea3SJordy Rose const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS()); 6057e3c3ea3SJordy Rose const llvm::APSInt &second = IntType.convert(*RHSValue); 60654569448SJordy Rose 607fa0734ecSArgyrios Kyrtzidis const llvm::APSInt *newRHS; 608fa0734ecSArgyrios Kyrtzidis if (lop == op) 609fa0734ecSArgyrios Kyrtzidis newRHS = BasicVals.evalAPSInt(BO_Add, first, second); 610fa0734ecSArgyrios Kyrtzidis else 611fa0734ecSArgyrios Kyrtzidis newRHS = BasicVals.evalAPSInt(BO_Sub, first, second); 61254569448SJordy Rose 61354569448SJordy Rose assert(newRHS && "Invalid operation despite common type!"); 61454569448SJordy Rose rhs = nonloc::ConcreteInt(*newRHS); 61554569448SJordy Rose lhs = nonloc::SymbolVal(symIntExpr->getLHS()); 61654569448SJordy Rose op = lop; 61754569448SJordy Rose continue; 618fa0734ecSArgyrios Kyrtzidis } 619fa0734ecSArgyrios Kyrtzidis } 620fa0734ecSArgyrios Kyrtzidis 62154569448SJordy Rose // Otherwise, make a SymIntExpr out of the expression. 62254569448SJordy Rose return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy); 62354569448SJordy Rose } 6243b4c3ea2SJordan Rose } 625fa0734ecSArgyrios Kyrtzidis 6263b4c3ea2SJordan Rose // Does the symbolic expression simplify to a constant? 6273b4c3ea2SJordan Rose // If so, "fold" the constant by setting 'lhs' to a ConcreteInt 6283b4c3ea2SJordan Rose // and try again. 62912294f8dSArtem Dergachev SVal simplifiedLhs = simplifySVal(state, lhs); 63012294f8dSArtem Dergachev if (simplifiedLhs != lhs) 63112294f8dSArtem Dergachev if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>()) { 63212294f8dSArtem Dergachev lhs = *simplifiedLhsAsNonLoc; 633fa0734ecSArgyrios Kyrtzidis continue; 634fa0734ecSArgyrios Kyrtzidis } 635fa0734ecSArgyrios Kyrtzidis 63654569448SJordy Rose // Is the RHS a constant? 63754569448SJordy Rose if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) 63854569448SJordy Rose return MakeSymIntVal(Sym, op, *RHSValue, resultTy); 639fa0734ecSArgyrios Kyrtzidis 6402bbccca9SAdam Balogh if (Optional<NonLoc> V = tryRearrange(state, op, lhs, rhs, resultTy)) 6412bbccca9SAdam Balogh return *V; 6422bbccca9SAdam Balogh 64354569448SJordy Rose // Give up -- this is not a symbolic expression we can handle. 644bd3e5dbfSGeorge Karpenkov return makeSymExprValNN(op, InputLHS, InputRHS, resultTy); 645fa0734ecSArgyrios Kyrtzidis } 646fa0734ecSArgyrios Kyrtzidis } 647fa0734ecSArgyrios Kyrtzidis } 648fa0734ecSArgyrios Kyrtzidis } 649fa0734ecSArgyrios Kyrtzidis 650bac964e1SAnna Zaks static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR, 651bac964e1SAnna Zaks const FieldRegion *RightFR, 652bac964e1SAnna Zaks BinaryOperator::Opcode op, 653bac964e1SAnna Zaks QualType resultTy, 654bac964e1SAnna Zaks SimpleSValBuilder &SVB) { 655bac964e1SAnna Zaks // Only comparisons are meaningful here! 656bac964e1SAnna Zaks if (!BinaryOperator::isComparisonOp(op)) 657bac964e1SAnna Zaks return UnknownVal(); 658bac964e1SAnna Zaks 659bac964e1SAnna Zaks // Next, see if the two FRs have the same super-region. 660bac964e1SAnna Zaks // FIXME: This doesn't handle casts yet, and simply stripping the casts 661bac964e1SAnna Zaks // doesn't help. 662bac964e1SAnna Zaks if (LeftFR->getSuperRegion() != RightFR->getSuperRegion()) 663bac964e1SAnna Zaks return UnknownVal(); 664bac964e1SAnna Zaks 665bac964e1SAnna Zaks const FieldDecl *LeftFD = LeftFR->getDecl(); 666bac964e1SAnna Zaks const FieldDecl *RightFD = RightFR->getDecl(); 667bac964e1SAnna Zaks const RecordDecl *RD = LeftFD->getParent(); 668bac964e1SAnna Zaks 669bac964e1SAnna Zaks // Make sure the two FRs are from the same kind of record. Just in case! 670bac964e1SAnna Zaks // FIXME: This is probably where inheritance would be a problem. 671bac964e1SAnna Zaks if (RD != RightFD->getParent()) 672bac964e1SAnna Zaks return UnknownVal(); 673bac964e1SAnna Zaks 674bac964e1SAnna Zaks // We know for sure that the two fields are not the same, since that 675bac964e1SAnna Zaks // would have given us the same SVal. 676bac964e1SAnna Zaks if (op == BO_EQ) 677bac964e1SAnna Zaks return SVB.makeTruthVal(false, resultTy); 678bac964e1SAnna Zaks if (op == BO_NE) 679bac964e1SAnna Zaks return SVB.makeTruthVal(true, resultTy); 680bac964e1SAnna Zaks 681bac964e1SAnna Zaks // Iterate through the fields and see which one comes first. 682bac964e1SAnna Zaks // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field 683bac964e1SAnna Zaks // members and the units in which bit-fields reside have addresses that 684bac964e1SAnna Zaks // increase in the order in which they are declared." 685bac964e1SAnna Zaks bool leftFirst = (op == BO_LT || op == BO_LE); 686e8a8baefSAaron Ballman for (const auto *I : RD->fields()) { 687e8a8baefSAaron Ballman if (I == LeftFD) 688bac964e1SAnna Zaks return SVB.makeTruthVal(leftFirst, resultTy); 689e8a8baefSAaron Ballman if (I == RightFD) 690bac964e1SAnna Zaks return SVB.makeTruthVal(!leftFirst, resultTy); 691bac964e1SAnna Zaks } 692bac964e1SAnna Zaks 693bac964e1SAnna Zaks llvm_unreachable("Fields not found in parent record's definition"); 694bac964e1SAnna Zaks } 695bac964e1SAnna Zaks 696fa0734ecSArgyrios Kyrtzidis // FIXME: all this logic will change if/when we have MemRegion::getLocation(). 69749b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state, 698fa0734ecSArgyrios Kyrtzidis BinaryOperator::Opcode op, 699fa0734ecSArgyrios Kyrtzidis Loc lhs, Loc rhs, 700fa0734ecSArgyrios Kyrtzidis QualType resultTy) { 701fa0734ecSArgyrios Kyrtzidis // Only comparisons and subtractions are valid operations on two pointers. 702fa0734ecSArgyrios Kyrtzidis // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15]. 703fa0734ecSArgyrios Kyrtzidis // However, if a pointer is casted to an integer, evalBinOpNN may end up 704fa0734ecSArgyrios Kyrtzidis // calling this function with another operation (PR7527). We don't attempt to 705fa0734ecSArgyrios Kyrtzidis // model this for now, but it could be useful, particularly when the 706fa0734ecSArgyrios Kyrtzidis // "location" is actually an integer value that's been passed through a void*. 707fa0734ecSArgyrios Kyrtzidis if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub)) 708fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 709fa0734ecSArgyrios Kyrtzidis 710fa0734ecSArgyrios Kyrtzidis // Special cases for when both sides are identical. 711fa0734ecSArgyrios Kyrtzidis if (lhs == rhs) { 712fa0734ecSArgyrios Kyrtzidis switch (op) { 713fa0734ecSArgyrios Kyrtzidis default: 71483d382b1SDavid Blaikie llvm_unreachable("Unimplemented operation for two identical values"); 715fa0734ecSArgyrios Kyrtzidis case BO_Sub: 716fa0734ecSArgyrios Kyrtzidis return makeZeroVal(resultTy); 717fa0734ecSArgyrios Kyrtzidis case BO_EQ: 718fa0734ecSArgyrios Kyrtzidis case BO_LE: 719fa0734ecSArgyrios Kyrtzidis case BO_GE: 720fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 721fa0734ecSArgyrios Kyrtzidis case BO_NE: 722fa0734ecSArgyrios Kyrtzidis case BO_LT: 723fa0734ecSArgyrios Kyrtzidis case BO_GT: 724fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 725fa0734ecSArgyrios Kyrtzidis } 726fa0734ecSArgyrios Kyrtzidis } 727fa0734ecSArgyrios Kyrtzidis 728fa0734ecSArgyrios Kyrtzidis switch (lhs.getSubKind()) { 729fa0734ecSArgyrios Kyrtzidis default: 73083d382b1SDavid Blaikie llvm_unreachable("Ordering not implemented for this Loc."); 731fa0734ecSArgyrios Kyrtzidis 732fa0734ecSArgyrios Kyrtzidis case loc::GotoLabelKind: 733fa0734ecSArgyrios Kyrtzidis // The only thing we know about labels is that they're non-null. 734fa0734ecSArgyrios Kyrtzidis if (rhs.isZeroConstant()) { 735fa0734ecSArgyrios Kyrtzidis switch (op) { 736fa0734ecSArgyrios Kyrtzidis default: 737fa0734ecSArgyrios Kyrtzidis break; 738fa0734ecSArgyrios Kyrtzidis case BO_Sub: 739*01ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 740fa0734ecSArgyrios Kyrtzidis case BO_EQ: 741fa0734ecSArgyrios Kyrtzidis case BO_LE: 742fa0734ecSArgyrios Kyrtzidis case BO_LT: 743fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 744fa0734ecSArgyrios Kyrtzidis case BO_NE: 745fa0734ecSArgyrios Kyrtzidis case BO_GT: 746fa0734ecSArgyrios Kyrtzidis case BO_GE: 747fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 748fa0734ecSArgyrios Kyrtzidis } 749fa0734ecSArgyrios Kyrtzidis } 750fa0734ecSArgyrios Kyrtzidis // There may be two labels for the same location, and a function region may 751fa0734ecSArgyrios Kyrtzidis // have the same address as a label at the start of the function (depending 752fa0734ecSArgyrios Kyrtzidis // on the ABI). 753fa0734ecSArgyrios Kyrtzidis // FIXME: we can probably do a comparison against other MemRegions, though. 754fa0734ecSArgyrios Kyrtzidis // FIXME: is there a way to tell if two labels refer to the same location? 755fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 756fa0734ecSArgyrios Kyrtzidis 757fa0734ecSArgyrios Kyrtzidis case loc::ConcreteIntKind: { 758fa0734ecSArgyrios Kyrtzidis // If one of the operands is a symbol and the other is a constant, 759fa0734ecSArgyrios Kyrtzidis // build an expression for use by the constraint manager. 760fa0734ecSArgyrios Kyrtzidis if (SymbolRef rSym = rhs.getAsLocSymbol()) { 761c0402c69SDominic Chen // We can only build expressions with symbols on the left, 762c0402c69SDominic Chen // so we need a reversible operator. 763c70f1d63SRichard Smith if (!BinaryOperator::isComparisonOp(op) || op == BO_Cmp) 764c0402c69SDominic Chen return UnknownVal(); 76535610d21SDominic Chen 766c0402c69SDominic Chen const llvm::APSInt &lVal = lhs.castAs<loc::ConcreteInt>().getValue(); 767604d0bbbSJordan Rose op = BinaryOperator::reverseComparisonOp(op); 768604d0bbbSJordan Rose return makeNonLoc(rSym, op, lVal, resultTy); 769fa0734ecSArgyrios Kyrtzidis } 770fa0734ecSArgyrios Kyrtzidis 771fa0734ecSArgyrios Kyrtzidis // If both operands are constants, just perform the operation. 77205785d16SDavid Blaikie if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) { 7732fdacbc5SDavid Blaikie SVal ResultVal = 7742fdacbc5SDavid Blaikie lhs.castAs<loc::ConcreteInt>().evalBinOp(BasicVals, op, *rInt); 7758eca04b2SJordan Rose if (Optional<NonLoc> Result = ResultVal.getAs<NonLoc>()) 776*01ddfa95SDenys Petrov return evalCast(*Result, resultTy, QualType{}); 7778eca04b2SJordan Rose 7788eca04b2SJordan Rose assert(!ResultVal.getAs<Loc>() && "Loc-Loc ops should not produce Locs"); 779fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 780fa0734ecSArgyrios Kyrtzidis } 781fa0734ecSArgyrios Kyrtzidis 782fa0734ecSArgyrios Kyrtzidis // Special case comparisons against NULL. 783fa0734ecSArgyrios Kyrtzidis // This must come after the test if the RHS is a symbol, which is used to 784fa0734ecSArgyrios Kyrtzidis // build constraints. The address of any non-symbolic region is guaranteed 785fa0734ecSArgyrios Kyrtzidis // to be non-NULL, as is any label. 7862fdacbc5SDavid Blaikie assert(rhs.getAs<loc::MemRegionVal>() || rhs.getAs<loc::GotoLabel>()); 787fa0734ecSArgyrios Kyrtzidis if (lhs.isZeroConstant()) { 788fa0734ecSArgyrios Kyrtzidis switch (op) { 789fa0734ecSArgyrios Kyrtzidis default: 790fa0734ecSArgyrios Kyrtzidis break; 791fa0734ecSArgyrios Kyrtzidis case BO_EQ: 792fa0734ecSArgyrios Kyrtzidis case BO_GT: 793fa0734ecSArgyrios Kyrtzidis case BO_GE: 794fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 795fa0734ecSArgyrios Kyrtzidis case BO_NE: 796fa0734ecSArgyrios Kyrtzidis case BO_LT: 797fa0734ecSArgyrios Kyrtzidis case BO_LE: 798fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 799fa0734ecSArgyrios Kyrtzidis } 800fa0734ecSArgyrios Kyrtzidis } 801fa0734ecSArgyrios Kyrtzidis 802fa0734ecSArgyrios Kyrtzidis // Comparing an arbitrary integer to a region or label address is 803fa0734ecSArgyrios Kyrtzidis // completely unknowable. 804fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 805fa0734ecSArgyrios Kyrtzidis } 80673f018e3SArtem Dergachev case loc::MemRegionValKind: { 80705785d16SDavid Blaikie if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) { 808fa0734ecSArgyrios Kyrtzidis // If one of the operands is a symbol and the other is a constant, 809fa0734ecSArgyrios Kyrtzidis // build an expression for use by the constraint manager. 810f4963ff1SAlexander Shaposhnikov if (SymbolRef lSym = lhs.getAsLocSymbol(true)) { 811f4963ff1SAlexander Shaposhnikov if (BinaryOperator::isComparisonOp(op)) 812fa0734ecSArgyrios Kyrtzidis return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy); 813f4963ff1SAlexander Shaposhnikov return UnknownVal(); 814f4963ff1SAlexander Shaposhnikov } 815fa0734ecSArgyrios Kyrtzidis // Special case comparisons to NULL. 816fa0734ecSArgyrios Kyrtzidis // This must come after the test if the LHS is a symbol, which is used to 817fa0734ecSArgyrios Kyrtzidis // build constraints. The address of any non-symbolic region is guaranteed 818fa0734ecSArgyrios Kyrtzidis // to be non-NULL. 819fa0734ecSArgyrios Kyrtzidis if (rInt->isZeroConstant()) { 820acd080b9SJordan Rose if (op == BO_Sub) 821*01ddfa95SDenys Petrov return evalCast(lhs, resultTy, QualType{}); 822acd080b9SJordan Rose 823acd080b9SJordan Rose if (BinaryOperator::isComparisonOp(op)) { 824acd080b9SJordan Rose QualType boolType = getContext().BoolTy; 825*01ddfa95SDenys Petrov NonLoc l = evalCast(lhs, boolType, QualType{}).castAs<NonLoc>(); 826acd080b9SJordan Rose NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>(); 827acd080b9SJordan Rose return evalBinOpNN(state, op, l, r, resultTy); 828fa0734ecSArgyrios Kyrtzidis } 829fa0734ecSArgyrios Kyrtzidis } 830fa0734ecSArgyrios Kyrtzidis 831fa0734ecSArgyrios Kyrtzidis // Comparing a region to an arbitrary integer is completely unknowable. 832fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 833fa0734ecSArgyrios Kyrtzidis } 834fa0734ecSArgyrios Kyrtzidis 835fa0734ecSArgyrios Kyrtzidis // Get both values as regions, if possible. 836fa0734ecSArgyrios Kyrtzidis const MemRegion *LeftMR = lhs.getAsRegion(); 83773f018e3SArtem Dergachev assert(LeftMR && "MemRegionValKind SVal doesn't have a region!"); 838fa0734ecSArgyrios Kyrtzidis 839fa0734ecSArgyrios Kyrtzidis const MemRegion *RightMR = rhs.getAsRegion(); 840fa0734ecSArgyrios Kyrtzidis if (!RightMR) 841fa0734ecSArgyrios Kyrtzidis // The RHS is probably a label, which in theory could address a region. 842fa0734ecSArgyrios Kyrtzidis // FIXME: we can probably make a more useful statement about non-code 843fa0734ecSArgyrios Kyrtzidis // regions, though. 844fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 845fa0734ecSArgyrios Kyrtzidis 846fa0734ecSArgyrios Kyrtzidis const MemRegion *LeftBase = LeftMR->getBaseRegion(); 847fa0734ecSArgyrios Kyrtzidis const MemRegion *RightBase = RightMR->getBaseRegion(); 8483b4c3ea2SJordan Rose const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace(); 8493b4c3ea2SJordan Rose const MemSpaceRegion *RightMS = RightBase->getMemorySpace(); 8503b4c3ea2SJordan Rose const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion(); 8513563fde6SAnna Zaks 8523563fde6SAnna Zaks // If the two regions are from different known memory spaces they cannot be 8533563fde6SAnna Zaks // equal. Also, assume that no symbolic region (whose memory space is 8543563fde6SAnna Zaks // unknown) is on the stack. 8553563fde6SAnna Zaks if (LeftMS != RightMS && 8563563fde6SAnna Zaks ((LeftMS != UnknownMS && RightMS != UnknownMS) || 8573563fde6SAnna Zaks (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) { 858fa0734ecSArgyrios Kyrtzidis switch (op) { 859fa0734ecSArgyrios Kyrtzidis default: 860fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 861fa0734ecSArgyrios Kyrtzidis case BO_EQ: 862fa0734ecSArgyrios Kyrtzidis return makeTruthVal(false, resultTy); 863fa0734ecSArgyrios Kyrtzidis case BO_NE: 864fa0734ecSArgyrios Kyrtzidis return makeTruthVal(true, resultTy); 865fa0734ecSArgyrios Kyrtzidis } 866fa0734ecSArgyrios Kyrtzidis } 867fa0734ecSArgyrios Kyrtzidis 8683563fde6SAnna Zaks // If both values wrap regions, see if they're from different base regions. 8693563fde6SAnna Zaks // Note, heap base symbolic regions are assumed to not alias with 8703563fde6SAnna Zaks // each other; for example, we assume that malloc returns different address 8713563fde6SAnna Zaks // on each invocation. 872aacc03c9SArtem Dergachev // FIXME: ObjC object pointers always reside on the heap, but currently 873aacc03c9SArtem Dergachev // we treat their memory space as unknown, because symbolic pointers 874aacc03c9SArtem Dergachev // to ObjC objects may alias. There should be a way to construct 875aacc03c9SArtem Dergachev // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker 876aacc03c9SArtem Dergachev // guesses memory space for ObjC object pointers manually instead of 877aacc03c9SArtem Dergachev // relying on us. 8783563fde6SAnna Zaks if (LeftBase != RightBase && 8793563fde6SAnna Zaks ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) || 880a7dcc996SAnna Zaks (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){ 8819d96f843STed Kremenek switch (op) { 8829d96f843STed Kremenek default: 8833563fde6SAnna Zaks return UnknownVal(); 8849d96f843STed Kremenek case BO_EQ: 8859d96f843STed Kremenek return makeTruthVal(false, resultTy); 8869d96f843STed Kremenek case BO_NE: 8879d96f843STed Kremenek return makeTruthVal(true, resultTy); 8889d96f843STed Kremenek } 8899d96f843STed Kremenek } 890fa0734ecSArgyrios Kyrtzidis 891bac964e1SAnna Zaks // Handle special cases for when both regions are element regions. 892fa0734ecSArgyrios Kyrtzidis const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR); 893bac964e1SAnna Zaks const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR); 894bac964e1SAnna Zaks if (RightER && LeftER) { 895fa0734ecSArgyrios Kyrtzidis // Next, see if the two ERs have the same super-region and matching types. 896fa0734ecSArgyrios Kyrtzidis // FIXME: This should do something useful even if the types don't match, 897fa0734ecSArgyrios Kyrtzidis // though if both indexes are constant the RegionRawOffset path will 898fa0734ecSArgyrios Kyrtzidis // give the correct answer. 899fa0734ecSArgyrios Kyrtzidis if (LeftER->getSuperRegion() == RightER->getSuperRegion() && 900fa0734ecSArgyrios Kyrtzidis LeftER->getElementType() == RightER->getElementType()) { 901fa0734ecSArgyrios Kyrtzidis // Get the left index and cast it to the correct type. 902fa0734ecSArgyrios Kyrtzidis // If the index is unknown or undefined, bail out here. 903fa0734ecSArgyrios Kyrtzidis SVal LeftIndexVal = LeftER->getIndex(); 90405785d16SDavid Blaikie Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>(); 905fa0734ecSArgyrios Kyrtzidis if (!LeftIndex) 906fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 907*01ddfa95SDenys Petrov LeftIndexVal = evalCast(*LeftIndex, ArrayIndexTy, QualType{}); 9082fdacbc5SDavid Blaikie LeftIndex = LeftIndexVal.getAs<NonLoc>(); 909fa0734ecSArgyrios Kyrtzidis if (!LeftIndex) 910fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 911fa0734ecSArgyrios Kyrtzidis 912fa0734ecSArgyrios Kyrtzidis // Do the same for the right index. 913fa0734ecSArgyrios Kyrtzidis SVal RightIndexVal = RightER->getIndex(); 91405785d16SDavid Blaikie Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>(); 915fa0734ecSArgyrios Kyrtzidis if (!RightIndex) 916fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 917*01ddfa95SDenys Petrov RightIndexVal = evalCast(*RightIndex, ArrayIndexTy, QualType{}); 9182fdacbc5SDavid Blaikie RightIndex = RightIndexVal.getAs<NonLoc>(); 919fa0734ecSArgyrios Kyrtzidis if (!RightIndex) 920fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 921fa0734ecSArgyrios Kyrtzidis 922fa0734ecSArgyrios Kyrtzidis // Actually perform the operation. 923fa0734ecSArgyrios Kyrtzidis // evalBinOpNN expects the two indexes to already be the right type. 924fa0734ecSArgyrios Kyrtzidis return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy); 925fa0734ecSArgyrios Kyrtzidis } 926bac964e1SAnna Zaks } 927fa0734ecSArgyrios Kyrtzidis 928bac964e1SAnna Zaks // Special handling of the FieldRegions, even with symbolic offsets. 929bac964e1SAnna Zaks const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR); 930bac964e1SAnna Zaks const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR); 931bac964e1SAnna Zaks if (RightFR && LeftFR) { 932bac964e1SAnna Zaks SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy, 933bac964e1SAnna Zaks *this); 934bac964e1SAnna Zaks if (!R.isUnknown()) 935bac964e1SAnna Zaks return R; 936bac964e1SAnna Zaks } 937bac964e1SAnna Zaks 938bac964e1SAnna Zaks // Compare the regions using the raw offsets. 939bac964e1SAnna Zaks RegionOffset LeftOffset = LeftMR->getAsOffset(); 940bac964e1SAnna Zaks RegionOffset RightOffset = RightMR->getAsOffset(); 941fa0734ecSArgyrios Kyrtzidis 9420dbb783cSCraig Topper if (LeftOffset.getRegion() != nullptr && 943bac964e1SAnna Zaks LeftOffset.getRegion() == RightOffset.getRegion() && 944bac964e1SAnna Zaks !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) { 945bac964e1SAnna Zaks int64_t left = LeftOffset.getOffset(); 946bac964e1SAnna Zaks int64_t right = RightOffset.getOffset(); 947fa0734ecSArgyrios Kyrtzidis 948fa0734ecSArgyrios Kyrtzidis switch (op) { 949fa0734ecSArgyrios Kyrtzidis default: 950fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 951fa0734ecSArgyrios Kyrtzidis case BO_LT: 952fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left < right, resultTy); 953fa0734ecSArgyrios Kyrtzidis case BO_GT: 954fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left > right, resultTy); 955fa0734ecSArgyrios Kyrtzidis case BO_LE: 956fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left <= right, resultTy); 957fa0734ecSArgyrios Kyrtzidis case BO_GE: 958fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left >= right, resultTy); 959fa0734ecSArgyrios Kyrtzidis case BO_EQ: 960fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left == right, resultTy); 961fa0734ecSArgyrios Kyrtzidis case BO_NE: 962fa0734ecSArgyrios Kyrtzidis return makeTruthVal(left != right, resultTy); 963fa0734ecSArgyrios Kyrtzidis } 964fa0734ecSArgyrios Kyrtzidis } 965fa0734ecSArgyrios Kyrtzidis 9663b4c3ea2SJordan Rose // At this point we're not going to get a good answer, but we can try 9673b4c3ea2SJordan Rose // conjuring an expression instead. 9683b4c3ea2SJordan Rose SymbolRef LHSSym = lhs.getAsLocSymbol(); 9693b4c3ea2SJordan Rose SymbolRef RHSSym = rhs.getAsLocSymbol(); 9703b4c3ea2SJordan Rose if (LHSSym && RHSSym) 9713b4c3ea2SJordan Rose return makeNonLoc(LHSSym, op, RHSSym, resultTy); 9723b4c3ea2SJordan Rose 973fa0734ecSArgyrios Kyrtzidis // If we get here, we have no way of comparing the regions. 974fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 975fa0734ecSArgyrios Kyrtzidis } 976fa0734ecSArgyrios Kyrtzidis } 977fa0734ecSArgyrios Kyrtzidis } 978fa0734ecSArgyrios Kyrtzidis 97949b1e38eSTed Kremenek SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state, 9809cbfdde2SValeriy Savchenko BinaryOperator::Opcode op, Loc lhs, 9819cbfdde2SValeriy Savchenko NonLoc rhs, QualType resultTy) { 98264c01f7bSDevin Coughlin if (op >= BO_PtrMemD && op <= BO_PtrMemI) { 98364c01f7bSDevin Coughlin if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) { 98464c01f7bSDevin Coughlin if (PTMSV->isNullMemberPointer()) 98564c01f7bSDevin Coughlin return UndefinedVal(); 9869cbfdde2SValeriy Savchenko 9879cbfdde2SValeriy Savchenko auto getFieldLValue = [&](const auto *FD) -> SVal { 98864c01f7bSDevin Coughlin SVal Result = lhs; 98964c01f7bSDevin Coughlin 99064c01f7bSDevin Coughlin for (const auto &I : *PTMSV) 99164c01f7bSDevin Coughlin Result = StateMgr.getStoreManager().evalDerivedToBase( 99264c01f7bSDevin Coughlin Result, I->getType(), I->isVirtual()); 9939cbfdde2SValeriy Savchenko 99464c01f7bSDevin Coughlin return state->getLValue(FD, Result); 9959cbfdde2SValeriy Savchenko }; 9969cbfdde2SValeriy Savchenko 9979cbfdde2SValeriy Savchenko if (const auto *FD = PTMSV->getDeclAs<FieldDecl>()) { 9989cbfdde2SValeriy Savchenko return getFieldLValue(FD); 9999cbfdde2SValeriy Savchenko } 10009cbfdde2SValeriy Savchenko if (const auto *FD = PTMSV->getDeclAs<IndirectFieldDecl>()) { 10019cbfdde2SValeriy Savchenko return getFieldLValue(FD); 100264c01f7bSDevin Coughlin } 100364c01f7bSDevin Coughlin } 100464c01f7bSDevin Coughlin 100564c01f7bSDevin Coughlin return rhs; 100664c01f7bSDevin Coughlin } 100764c01f7bSDevin Coughlin 1008686df322SJordan Rose assert(!BinaryOperator::isComparisonOp(op) && 1009686df322SJordan Rose "arguments to comparison ops must be of the same type"); 1010fa0734ecSArgyrios Kyrtzidis 1011fa0734ecSArgyrios Kyrtzidis // Special case: rhs is a zero constant. 1012fa0734ecSArgyrios Kyrtzidis if (rhs.isZeroConstant()) 1013fa0734ecSArgyrios Kyrtzidis return lhs; 1014fa0734ecSArgyrios Kyrtzidis 101521524676SGabor Horvath // Perserve the null pointer so that it can be found by the DerefChecker. 101621524676SGabor Horvath if (lhs.isZeroConstant()) 101721524676SGabor Horvath return lhs; 101821524676SGabor Horvath 1019fa0734ecSArgyrios Kyrtzidis // We are dealing with pointer arithmetic. 1020fa0734ecSArgyrios Kyrtzidis 1021fa0734ecSArgyrios Kyrtzidis // Handle pointer arithmetic on constant values. 102205785d16SDavid Blaikie if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) { 102305785d16SDavid Blaikie if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) { 1024fa0734ecSArgyrios Kyrtzidis const llvm::APSInt &leftI = lhsInt->getValue(); 1025fa0734ecSArgyrios Kyrtzidis assert(leftI.isUnsigned()); 1026fa0734ecSArgyrios Kyrtzidis llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true); 1027fa0734ecSArgyrios Kyrtzidis 1028fa0734ecSArgyrios Kyrtzidis // Convert the bitwidth of rightI. This should deal with overflow 1029fa0734ecSArgyrios Kyrtzidis // since we are dealing with concrete values. 1030fa0734ecSArgyrios Kyrtzidis rightI = rightI.extOrTrunc(leftI.getBitWidth()); 1031fa0734ecSArgyrios Kyrtzidis 1032fa0734ecSArgyrios Kyrtzidis // Offset the increment by the pointer size. 1033fa0734ecSArgyrios Kyrtzidis llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true); 103421524676SGabor Horvath QualType pointeeType = resultTy->getPointeeType(); 103521524676SGabor Horvath Multiplicand = getContext().getTypeSizeInChars(pointeeType).getQuantity(); 1036fa0734ecSArgyrios Kyrtzidis rightI *= Multiplicand; 1037fa0734ecSArgyrios Kyrtzidis 1038fa0734ecSArgyrios Kyrtzidis // Compute the adjusted pointer. 1039fa0734ecSArgyrios Kyrtzidis switch (op) { 1040fa0734ecSArgyrios Kyrtzidis case BO_Add: 1041fa0734ecSArgyrios Kyrtzidis rightI = leftI + rightI; 1042fa0734ecSArgyrios Kyrtzidis break; 1043fa0734ecSArgyrios Kyrtzidis case BO_Sub: 1044fa0734ecSArgyrios Kyrtzidis rightI = leftI - rightI; 1045fa0734ecSArgyrios Kyrtzidis break; 1046fa0734ecSArgyrios Kyrtzidis default: 1047fa0734ecSArgyrios Kyrtzidis llvm_unreachable("Invalid pointer arithmetic operation"); 1048fa0734ecSArgyrios Kyrtzidis } 1049fa0734ecSArgyrios Kyrtzidis return loc::ConcreteInt(getBasicValueFactory().getValue(rightI)); 1050fa0734ecSArgyrios Kyrtzidis } 1051fa0734ecSArgyrios Kyrtzidis } 1052fa0734ecSArgyrios Kyrtzidis 1053fa0734ecSArgyrios Kyrtzidis // Handle cases where 'lhs' is a region. 1054fa0734ecSArgyrios Kyrtzidis if (const MemRegion *region = lhs.getAsRegion()) { 10552fdacbc5SDavid Blaikie rhs = convertToArrayIndex(rhs).castAs<NonLoc>(); 1056fa0734ecSArgyrios Kyrtzidis SVal index = UnknownVal(); 10576dd11048SArtem Dergachev const SubRegion *superR = nullptr; 10587333a9eaSArtem Dergachev // We need to know the type of the pointer in order to add an integer to it. 10597333a9eaSArtem Dergachev // Depending on the type, different amount of bytes is added. 1060fa0734ecSArgyrios Kyrtzidis QualType elementType; 1061fa0734ecSArgyrios Kyrtzidis 1062fa0734ecSArgyrios Kyrtzidis if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) { 106357a4a152STed Kremenek assert(op == BO_Add || op == BO_Sub); 106457a4a152STed Kremenek index = evalBinOpNN(state, op, elemReg->getIndex(), rhs, 1065fa0734ecSArgyrios Kyrtzidis getArrayIndexType()); 10666dd11048SArtem Dergachev superR = cast<SubRegion>(elemReg->getSuperRegion()); 1067fa0734ecSArgyrios Kyrtzidis elementType = elemReg->getElementType(); 1068fa0734ecSArgyrios Kyrtzidis } 1069fa0734ecSArgyrios Kyrtzidis else if (isa<SubRegion>(region)) { 1070c4b28a8fSGabor Horvath assert(op == BO_Add || op == BO_Sub); 1071c4b28a8fSGabor Horvath index = (op == BO_Add) ? rhs : evalMinus(rhs); 10726dd11048SArtem Dergachev superR = cast<SubRegion>(region); 10737333a9eaSArtem Dergachev // TODO: Is this actually reliable? Maybe improving our MemRegion 10747333a9eaSArtem Dergachev // hierarchy to provide typed regions for all non-void pointers would be 10757333a9eaSArtem Dergachev // better. For instance, we cannot extend this towards LocAsInteger 10767333a9eaSArtem Dergachev // operations, where result type of the expression is integer. 1077d1a08b6eSJordan Rose if (resultTy->isAnyPointerType()) 1078d1a08b6eSJordan Rose elementType = resultTy->getPointeeType(); 1079fa0734ecSArgyrios Kyrtzidis } 1080fa0734ecSArgyrios Kyrtzidis 1081df1bb8a6SArtem Dergachev // Represent arithmetic on void pointers as arithmetic on char pointers. 1082df1bb8a6SArtem Dergachev // It is fine when a TypedValueRegion of char value type represents 1083df1bb8a6SArtem Dergachev // a void pointer. Note that arithmetic on void pointers is a GCC extension. 1084df1bb8a6SArtem Dergachev if (elementType->isVoidType()) 1085df1bb8a6SArtem Dergachev elementType = getContext().CharTy; 1086df1bb8a6SArtem Dergachev 108705785d16SDavid Blaikie if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) { 1088fa0734ecSArgyrios Kyrtzidis return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV, 1089fa0734ecSArgyrios Kyrtzidis superR, getContext())); 1090fa0734ecSArgyrios Kyrtzidis } 1091fa0734ecSArgyrios Kyrtzidis } 1092fa0734ecSArgyrios Kyrtzidis return UnknownVal(); 1093fa0734ecSArgyrios Kyrtzidis } 1094fa0734ecSArgyrios Kyrtzidis 109549b1e38eSTed Kremenek const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state, 1096fa0734ecSArgyrios Kyrtzidis SVal V) { 10979ff67a9dSGeorge Karpenkov V = simplifySVal(state, V); 1098fa0734ecSArgyrios Kyrtzidis if (V.isUnknownOrUndef()) 10990dbb783cSCraig Topper return nullptr; 1100fa0734ecSArgyrios Kyrtzidis 110105785d16SDavid Blaikie if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>()) 1102fa0734ecSArgyrios Kyrtzidis return &X->getValue(); 1103fa0734ecSArgyrios Kyrtzidis 110405785d16SDavid Blaikie if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>()) 1105fa0734ecSArgyrios Kyrtzidis return &X->getValue(); 1106fa0734ecSArgyrios Kyrtzidis 1107fa0734ecSArgyrios Kyrtzidis if (SymbolRef Sym = V.getAsSymbol()) 1108244e1d7dSTed Kremenek return state->getConstraintManager().getSymVal(state, Sym); 1109fa0734ecSArgyrios Kyrtzidis 1110c0402c69SDominic Chen // FIXME: Add support for SymExprs. 11110dbb783cSCraig Topper return nullptr; 1112fa0734ecSArgyrios Kyrtzidis } 111312294f8dSArtem Dergachev 111412294f8dSArtem Dergachev SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) { 111512294f8dSArtem Dergachev // For now, this function tries to constant-fold symbols inside a 111612294f8dSArtem Dergachev // nonloc::SymbolVal, and does nothing else. More simplifications should 111712294f8dSArtem Dergachev // be possible, such as constant-folding an index in an ElementRegion. 111812294f8dSArtem Dergachev 111912294f8dSArtem Dergachev class Simplifier : public FullSValVisitor<Simplifier, SVal> { 112012294f8dSArtem Dergachev ProgramStateRef State; 112112294f8dSArtem Dergachev SValBuilder &SVB; 112212294f8dSArtem Dergachev 112322746d7dSArtem Dergachev // Cache results for the lifetime of the Simplifier. Results change every 112422746d7dSArtem Dergachev // time new constraints are added to the program state, which is the whole 112522746d7dSArtem Dergachev // point of simplifying, and for that very reason it's pointless to maintain 112622746d7dSArtem Dergachev // the same cache for the duration of the whole analysis. 112722746d7dSArtem Dergachev llvm::DenseMap<SymbolRef, SVal> Cached; 112822746d7dSArtem Dergachev 112916a1f64cSArtem Dergachev static bool isUnchanged(SymbolRef Sym, SVal Val) { 113016a1f64cSArtem Dergachev return Sym == Val.getAsSymbol(); 113116a1f64cSArtem Dergachev } 113216a1f64cSArtem Dergachev 11339fe9a95fSArtem Dergachev SVal cache(SymbolRef Sym, SVal V) { 11349fe9a95fSArtem Dergachev Cached[Sym] = V; 11359fe9a95fSArtem Dergachev return V; 11369fe9a95fSArtem Dergachev } 11379fe9a95fSArtem Dergachev 11389fe9a95fSArtem Dergachev SVal skip(SymbolRef Sym) { 11399fe9a95fSArtem Dergachev return cache(Sym, SVB.makeSymbolVal(Sym)); 11409fe9a95fSArtem Dergachev } 11419fe9a95fSArtem Dergachev 114212294f8dSArtem Dergachev public: 114312294f8dSArtem Dergachev Simplifier(ProgramStateRef State) 114412294f8dSArtem Dergachev : State(State), SVB(State->getStateManager().getSValBuilder()) {} 114512294f8dSArtem Dergachev 114612294f8dSArtem Dergachev SVal VisitSymbolData(const SymbolData *S) { 11479fe9a95fSArtem Dergachev // No cache here. 114812294f8dSArtem Dergachev if (const llvm::APSInt *I = 1149d1163790SArtem Dergachev SVB.getKnownValue(State, SVB.makeSymbolVal(S))) 115012294f8dSArtem Dergachev return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I) 115112294f8dSArtem Dergachev : (SVal)SVB.makeIntVal(*I); 115216a1f64cSArtem Dergachev return SVB.makeSymbolVal(S); 115312294f8dSArtem Dergachev } 115412294f8dSArtem Dergachev 1155c0402c69SDominic Chen // TODO: Support SymbolCast. Support IntSymExpr when/if we actually 1156c0402c69SDominic Chen // start producing them. 115712294f8dSArtem Dergachev 115812294f8dSArtem Dergachev SVal VisitSymIntExpr(const SymIntExpr *S) { 115922746d7dSArtem Dergachev auto I = Cached.find(S); 116022746d7dSArtem Dergachev if (I != Cached.end()) 116122746d7dSArtem Dergachev return I->second; 116222746d7dSArtem Dergachev 116312294f8dSArtem Dergachev SVal LHS = Visit(S->getLHS()); 11649fe9a95fSArtem Dergachev if (isUnchanged(S->getLHS(), LHS)) 11659fe9a95fSArtem Dergachev return skip(S); 11669fe9a95fSArtem Dergachev 116712294f8dSArtem Dergachev SVal RHS; 116812294f8dSArtem Dergachev // By looking at the APSInt in the right-hand side of S, we cannot 116912294f8dSArtem Dergachev // figure out if it should be treated as a Loc or as a NonLoc. 117012294f8dSArtem Dergachev // So make our guess by recalling that we cannot multiply pointers 117112294f8dSArtem Dergachev // or compare a pointer to an integer. 117212294f8dSArtem Dergachev if (Loc::isLocType(S->getLHS()->getType()) && 117312294f8dSArtem Dergachev BinaryOperator::isComparisonOp(S->getOpcode())) { 117412294f8dSArtem Dergachev // The usual conversion of $sym to &SymRegion{$sym}, as they have 117512294f8dSArtem Dergachev // the same meaning for Loc-type symbols, but the latter form 117612294f8dSArtem Dergachev // is preferred in SVal computations for being Loc itself. 117712294f8dSArtem Dergachev if (SymbolRef Sym = LHS.getAsSymbol()) { 117812294f8dSArtem Dergachev assert(Loc::isLocType(Sym->getType())); 117912294f8dSArtem Dergachev LHS = SVB.makeLoc(Sym); 118012294f8dSArtem Dergachev } 118112294f8dSArtem Dergachev RHS = SVB.makeIntLocVal(S->getRHS()); 118212294f8dSArtem Dergachev } else { 118312294f8dSArtem Dergachev RHS = SVB.makeIntVal(S->getRHS()); 118412294f8dSArtem Dergachev } 118522746d7dSArtem Dergachev 11869fe9a95fSArtem Dergachev return cache( 11879fe9a95fSArtem Dergachev S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType())); 118812294f8dSArtem Dergachev } 118912294f8dSArtem Dergachev 119012294f8dSArtem Dergachev SVal VisitSymSymExpr(const SymSymExpr *S) { 119122746d7dSArtem Dergachev auto I = Cached.find(S); 119222746d7dSArtem Dergachev if (I != Cached.end()) 119322746d7dSArtem Dergachev return I->second; 119422746d7dSArtem Dergachev 119505220a90SArtem Dergachev // For now don't try to simplify mixed Loc/NonLoc expressions 119605220a90SArtem Dergachev // because they often appear from LocAsInteger operations 119705220a90SArtem Dergachev // and we don't know how to combine a LocAsInteger 119805220a90SArtem Dergachev // with a concrete value. 119905220a90SArtem Dergachev if (Loc::isLocType(S->getLHS()->getType()) != 12009fe9a95fSArtem Dergachev Loc::isLocType(S->getRHS()->getType())) 12019fe9a95fSArtem Dergachev return skip(S); 120205220a90SArtem Dergachev 120312294f8dSArtem Dergachev SVal LHS = Visit(S->getLHS()); 120412294f8dSArtem Dergachev SVal RHS = Visit(S->getRHS()); 12059fe9a95fSArtem Dergachev if (isUnchanged(S->getLHS(), LHS) && isUnchanged(S->getRHS(), RHS)) 12069fe9a95fSArtem Dergachev return skip(S); 12079fe9a95fSArtem Dergachev 12089fe9a95fSArtem Dergachev return cache( 12099fe9a95fSArtem Dergachev S, SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType())); 121012294f8dSArtem Dergachev } 121112294f8dSArtem Dergachev 121212294f8dSArtem Dergachev SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); } 121312294f8dSArtem Dergachev 121412294f8dSArtem Dergachev SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); } 121512294f8dSArtem Dergachev 121612294f8dSArtem Dergachev SVal VisitNonLocSymbolVal(nonloc::SymbolVal V) { 121712294f8dSArtem Dergachev // Simplification is much more costly than computing complexity. 121812294f8dSArtem Dergachev // For high complexity, it may be not worth it. 121912294f8dSArtem Dergachev return Visit(V.getSymbol()); 122012294f8dSArtem Dergachev } 122112294f8dSArtem Dergachev 122212294f8dSArtem Dergachev SVal VisitSVal(SVal V) { return V; } 122312294f8dSArtem Dergachev }; 122412294f8dSArtem Dergachev 122516a1f64cSArtem Dergachev // A crude way of preventing this function from calling itself from evalBinOp. 122616a1f64cSArtem Dergachev static bool isReentering = false; 122716a1f64cSArtem Dergachev if (isReentering) 122816a1f64cSArtem Dergachev return V; 122916a1f64cSArtem Dergachev 123016a1f64cSArtem Dergachev isReentering = true; 123116a1f64cSArtem Dergachev SVal SimplifiedV = Simplifier(State).Visit(V); 123216a1f64cSArtem Dergachev isReentering = false; 123316a1f64cSArtem Dergachev 123416a1f64cSArtem Dergachev return SimplifiedV; 123512294f8dSArtem Dergachev } 1236