1 // SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- C++ -*-
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines SimpleSValBuilder, a basic implementation of SValBuilder.
12 //===----------------------------------------------------------------------===//
14 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
15 #include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
16 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
17 #include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h"
19 using namespace clang;
23 class SimpleSValBuilder : public SValBuilder {
25 SVal dispatchCast(SVal val, QualType castTy) override;
26 SVal evalCastFromNonLoc(NonLoc val, QualType castTy) override;
27 SVal evalCastFromLoc(Loc val, QualType castTy) override;
30 SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
31 ProgramStateManager &stateMgr)
32 : SValBuilder(alloc, context, stateMgr) {}
33 ~SimpleSValBuilder() override {}
35 SVal evalMinus(NonLoc val) override;
36 SVal evalComplement(NonLoc val) override;
37 SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
38 NonLoc lhs, NonLoc rhs, QualType resultTy) override;
39 SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
40 Loc lhs, Loc rhs, QualType resultTy) override;
41 SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
42 Loc lhs, NonLoc rhs, QualType resultTy) override;
44 /// getKnownValue - evaluates a given SVal. If the SVal has only one possible
45 /// (integer) value, that value is returned. Otherwise, returns NULL.
46 const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override;
48 /// Recursively descends into symbolic expressions and replaces symbols
49 /// with their known values (in the sense of the getKnownValue() method).
50 SVal simplifySVal(ProgramStateRef State, SVal V) override;
52 SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
53 const llvm::APSInt &RHS, QualType resultTy);
55 } // end anonymous namespace
57 SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
59 ProgramStateManager &stateMgr) {
60 return new SimpleSValBuilder(alloc, context, stateMgr);
63 //===----------------------------------------------------------------------===//
64 // Transfer function for Casts.
65 //===----------------------------------------------------------------------===//
67 SVal SimpleSValBuilder::dispatchCast(SVal Val, QualType CastTy) {
68 assert(Val.getAs<Loc>() || Val.getAs<NonLoc>());
69 return Val.getAs<Loc>() ? evalCastFromLoc(Val.castAs<Loc>(), CastTy)
70 : evalCastFromNonLoc(Val.castAs<NonLoc>(), CastTy);
73 SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
75 bool isLocType = Loc::isLocType(castTy);
77 if (val.getAs<nonloc::PointerToMember>())
80 if (Optional<nonloc::LocAsInteger> LI = val.getAs<nonloc::LocAsInteger>()) {
84 // FIXME: Correctly support promotions/truncations.
85 unsigned castSize = Context.getTypeSize(castTy);
86 if (castSize == LI->getNumBits())
88 return makeLocAsInteger(LI->getLoc(), castSize);
91 if (const SymExpr *se = val.getAsSymbolicExpression()) {
92 QualType T = Context.getCanonicalType(se->getType());
93 // If types are the same or both are integers, ignore the cast.
94 // FIXME: Remove this hack when we support symbolic truncation/extension.
95 // HACK: If both castTy and T are integers, ignore the cast. This is
96 // not a permanent solution. Eventually we want to precisely handle
97 // extension/truncation of symbolic integers. This prevents us from losing
98 // precision when we assign 'x = y' and 'y' is symbolic and x and y are
99 // different integer types.
100 if (haveSameType(T, castTy))
104 return makeNonLoc(se, T, castTy);
108 // If value is a non-integer constant, produce unknown.
109 if (!val.getAs<nonloc::ConcreteInt>())
112 // Handle casts to a boolean type.
113 if (castTy->isBooleanType()) {
114 bool b = val.castAs<nonloc::ConcreteInt>().getValue().getBoolValue();
115 return makeTruthVal(b, castTy);
118 // Only handle casts from integers to integers - if val is an integer constant
119 // being cast to a non-integer type, produce unknown.
120 if (!isLocType && !castTy->isIntegralOrEnumerationType())
123 llvm::APSInt i = val.castAs<nonloc::ConcreteInt>().getValue();
124 BasicVals.getAPSIntType(castTy).apply(i);
127 return makeIntLocVal(i);
129 return makeIntVal(i);
132 SVal SimpleSValBuilder::evalCastFromLoc(Loc val, QualType castTy) {
134 // Casts from pointers -> pointers, just return the lval.
136 // Casts from pointers -> references, just return the lval. These
137 // can be introduced by the frontend for corner cases, e.g
138 // casting from va_list* to __builtin_va_list&.
140 if (Loc::isLocType(castTy) || castTy->isReferenceType())
143 // FIXME: Handle transparent unions where a value can be "transparently"
144 // lifted into a union type.
145 if (castTy->isUnionType())
148 // Casting a Loc to a bool will almost always be true,
149 // unless this is a weak function or a symbolic region.
150 if (castTy->isBooleanType()) {
151 switch (val.getSubKind()) {
152 case loc::MemRegionValKind: {
153 const MemRegion *R = val.castAs<loc::MemRegionVal>().getRegion();
154 if (const FunctionCodeRegion *FTR = dyn_cast<FunctionCodeRegion>(R))
155 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FTR->getDecl()))
157 // FIXME: Currently we are using an extent symbol here,
158 // because there are no generic region address metadata
159 // symbols to use, only content metadata.
160 return nonloc::SymbolVal(SymMgr.getExtentSymbol(FTR));
162 if (const SymbolicRegion *SymR = R->getSymbolicBase())
163 return nonloc::SymbolVal(SymR->getSymbol());
168 case loc::GotoLabelKind:
169 // Labels and non-symbolic memory regions are always true.
170 return makeTruthVal(true, castTy);
174 if (castTy->isIntegralOrEnumerationType()) {
175 unsigned BitWidth = Context.getTypeSize(castTy);
177 if (!val.getAs<loc::ConcreteInt>())
178 return makeLocAsInteger(val, BitWidth);
180 llvm::APSInt i = val.castAs<loc::ConcreteInt>().getValue();
181 BasicVals.getAPSIntType(castTy).apply(i);
182 return makeIntVal(i);
185 // All other cases: return 'UnknownVal'. This includes casting pointers
186 // to floats, which is probably badness it itself, but this is a good
187 // intermediate solution until we do something better.
191 //===----------------------------------------------------------------------===//
192 // Transfer function for unary operators.
193 //===----------------------------------------------------------------------===//
195 SVal SimpleSValBuilder::evalMinus(NonLoc val) {
196 switch (val.getSubKind()) {
197 case nonloc::ConcreteIntKind:
198 return val.castAs<nonloc::ConcreteInt>().evalMinus(*this);
204 SVal SimpleSValBuilder::evalComplement(NonLoc X) {
205 switch (X.getSubKind()) {
206 case nonloc::ConcreteIntKind:
207 return X.castAs<nonloc::ConcreteInt>().evalComplement(*this);
213 //===----------------------------------------------------------------------===//
214 // Transfer function for binary operators.
215 //===----------------------------------------------------------------------===//
217 SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
218 BinaryOperator::Opcode op,
219 const llvm::APSInt &RHS,
221 bool isIdempotent = false;
223 // Check for a few special cases with known reductions first.
226 // We can't reduce this case; just treat it normally.
231 return makeIntVal(0, resultTy);
238 // This is also handled elsewhere.
239 return UndefinedVal();
246 // This is also handled elsewhere.
247 return UndefinedVal();
249 return makeIntVal(0, resultTy);
256 // a+0, a-0, a<<0, a>>0, a^0
263 return makeIntVal(0, resultTy);
264 else if (RHS.isAllOnesValue())
271 else if (RHS.isAllOnesValue()) {
272 const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
273 return nonloc::ConcreteInt(Result);
278 // Idempotent ops (like a*1) can still change the type of an expression.
279 // Wrap the LHS up in a NonLoc again and let evalCastFromNonLoc do the
282 return evalCastFromNonLoc(nonloc::SymbolVal(LHS), resultTy);
284 // If we reach this point, the expression cannot be simplified.
285 // Make a SymbolVal for the entire expression, after converting the RHS.
286 const llvm::APSInt *ConvertedRHS = &RHS;
287 if (BinaryOperator::isComparisonOp(op)) {
288 // We're looking for a type big enough to compare the symbolic value
289 // with the given constant.
290 // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
291 ASTContext &Ctx = getContext();
292 QualType SymbolType = LHS->getType();
293 uint64_t ValWidth = RHS.getBitWidth();
294 uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
296 if (ValWidth < TypeWidth) {
297 // If the value is too small, extend it.
298 ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
299 } else if (ValWidth == TypeWidth) {
300 // If the value is signed but the symbol is unsigned, do the comparison
301 // in unsigned space. [C99 6.3.1.8]
302 // (For the opposite case, the value is already unsigned.)
303 if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
304 ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
307 ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
309 return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
312 SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
313 BinaryOperator::Opcode op,
314 NonLoc lhs, NonLoc rhs,
316 NonLoc InputLHS = lhs;
317 NonLoc InputRHS = rhs;
319 // Handle trivial case where left-side and right-side are the same.
327 return makeTruthVal(true, resultTy);
331 return makeTruthVal(false, resultTy);
334 if (resultTy->isIntegralOrEnumerationType())
335 return makeIntVal(0, resultTy);
336 return evalCastFromNonLoc(makeIntVal(0, /*Unsigned=*/false), resultTy);
339 return evalCastFromNonLoc(lhs, resultTy);
343 switch (lhs.getSubKind()) {
345 return makeSymExprValNN(state, op, lhs, rhs, resultTy);
346 case nonloc::PointerToMemberKind: {
347 assert(rhs.getSubKind() == nonloc::PointerToMemberKind &&
348 "Both SVals should have pointer-to-member-type");
349 auto LPTM = lhs.castAs<nonloc::PointerToMember>(),
350 RPTM = rhs.castAs<nonloc::PointerToMember>();
351 auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData();
354 return makeTruthVal(LPTMD == RPTMD, resultTy);
356 return makeTruthVal(LPTMD != RPTMD, resultTy);
361 case nonloc::LocAsIntegerKind: {
362 Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc();
363 switch (rhs.getSubKind()) {
364 case nonloc::LocAsIntegerKind:
365 return evalBinOpLL(state, op, lhsL,
366 rhs.castAs<nonloc::LocAsInteger>().getLoc(),
368 case nonloc::ConcreteIntKind: {
369 // Transform the integer into a location and compare.
370 // FIXME: This only makes sense for comparisons. If we want to, say,
371 // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it,
372 // then pack it back into a LocAsInteger.
373 llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue();
374 BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
375 return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
380 return makeTruthVal(false, resultTy);
382 return makeTruthVal(true, resultTy);
384 // This case also handles pointer arithmetic.
385 return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
389 case nonloc::ConcreteIntKind: {
390 llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
392 // If we're dealing with two known constants, just perform the operation.
393 if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) {
394 llvm::APSInt RHSValue = *KnownRHSValue;
395 if (BinaryOperator::isComparisonOp(op)) {
396 // We're looking for a type big enough to compare the two values.
397 // FIXME: This is not correct. char + short will result in a promotion
398 // to int. Unfortunately we have lost types by this point.
399 APSIntType CompareType = std::max(APSIntType(LHSValue),
400 APSIntType(RHSValue));
401 CompareType.apply(LHSValue);
402 CompareType.apply(RHSValue);
403 } else if (!BinaryOperator::isShiftOp(op)) {
404 APSIntType IntType = BasicVals.getAPSIntType(resultTy);
405 IntType.apply(LHSValue);
406 IntType.apply(RHSValue);
409 const llvm::APSInt *Result =
410 BasicVals.evalAPSInt(op, LHSValue, RHSValue);
412 return UndefinedVal();
414 return nonloc::ConcreteInt(*Result);
417 // Swap the left and right sides and flip the operator if doing so
418 // allows us to better reason about the expression (this is a form
419 // of expression canonicalization).
420 // While we're at it, catch some special cases for non-commutative ops.
426 op = BinaryOperator::reverseComparisonOp(op);
439 if (LHSValue.isAllOnesValue() && LHSValue.isSigned())
440 return evalCastFromNonLoc(lhs, resultTy);
445 return evalCastFromNonLoc(lhs, resultTy);
446 return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
448 return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
451 case nonloc::SymbolValKind: {
452 // We only handle LHS as simple symbols or SymIntExprs.
453 SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
455 // LHS is a symbolic expression.
456 if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
458 // Is this a logical not? (!x is represented as x == 0.)
459 if (op == BO_EQ && rhs.isZeroConstant()) {
460 // We know how to negate certain expressions. Simplify them here.
462 BinaryOperator::Opcode opc = symIntExpr->getOpcode();
465 // We don't know how to negate this operation.
466 // Just handle it as if it were a normal comparison to 0.
470 llvm_unreachable("Logical operators handled by branching logic.");
483 llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
486 llvm_unreachable("Pointer arithmetic not handled here.");
493 assert(resultTy->isBooleanType() ||
494 resultTy == getConditionType());
495 assert(symIntExpr->getType()->isBooleanType() ||
496 getContext().hasSameUnqualifiedType(symIntExpr->getType(),
497 getConditionType()));
498 // Negate the comparison and make a value.
499 opc = BinaryOperator::negateComparisonOp(opc);
500 return makeNonLoc(symIntExpr->getLHS(), opc,
501 symIntExpr->getRHS(), resultTy);
505 // For now, only handle expressions whose RHS is a constant.
506 if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) {
507 // If both the LHS and the current expression are additive,
508 // fold their constants and try again.
509 if (BinaryOperator::isAdditiveOp(op)) {
510 BinaryOperator::Opcode lop = symIntExpr->getOpcode();
511 if (BinaryOperator::isAdditiveOp(lop)) {
512 // Convert the two constants to a common type, then combine them.
514 // resultTy may not be the best type to convert to, but it's
515 // probably the best choice in expressions with mixed type
516 // (such as x+1U+2LL). The rules for implicit conversions should
517 // choose a reasonable type to preserve the expression, and will
518 // at least match how the value is going to be used.
519 APSIntType IntType = BasicVals.getAPSIntType(resultTy);
520 const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
521 const llvm::APSInt &second = IntType.convert(*RHSValue);
523 const llvm::APSInt *newRHS;
525 newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
527 newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
529 assert(newRHS && "Invalid operation despite common type!");
530 rhs = nonloc::ConcreteInt(*newRHS);
531 lhs = nonloc::SymbolVal(symIntExpr->getLHS());
537 // Otherwise, make a SymIntExpr out of the expression.
538 return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
542 // Does the symbolic expression simplify to a constant?
543 // If so, "fold" the constant by setting 'lhs' to a ConcreteInt
545 SVal simplifiedLhs = simplifySVal(state, lhs);
546 if (simplifiedLhs != lhs)
547 if (auto simplifiedLhsAsNonLoc = simplifiedLhs.getAs<NonLoc>()) {
548 lhs = *simplifiedLhsAsNonLoc;
552 // Is the RHS a constant?
553 if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
554 return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
556 // Give up -- this is not a symbolic expression we can handle.
557 return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
563 static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR,
564 const FieldRegion *RightFR,
565 BinaryOperator::Opcode op,
567 SimpleSValBuilder &SVB) {
568 // Only comparisons are meaningful here!
569 if (!BinaryOperator::isComparisonOp(op))
572 // Next, see if the two FRs have the same super-region.
573 // FIXME: This doesn't handle casts yet, and simply stripping the casts
575 if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
578 const FieldDecl *LeftFD = LeftFR->getDecl();
579 const FieldDecl *RightFD = RightFR->getDecl();
580 const RecordDecl *RD = LeftFD->getParent();
582 // Make sure the two FRs are from the same kind of record. Just in case!
583 // FIXME: This is probably where inheritance would be a problem.
584 if (RD != RightFD->getParent())
587 // We know for sure that the two fields are not the same, since that
588 // would have given us the same SVal.
590 return SVB.makeTruthVal(false, resultTy);
592 return SVB.makeTruthVal(true, resultTy);
594 // Iterate through the fields and see which one comes first.
595 // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
596 // members and the units in which bit-fields reside have addresses that
597 // increase in the order in which they are declared."
598 bool leftFirst = (op == BO_LT || op == BO_LE);
599 for (const auto *I : RD->fields()) {
601 return SVB.makeTruthVal(leftFirst, resultTy);
603 return SVB.makeTruthVal(!leftFirst, resultTy);
606 llvm_unreachable("Fields not found in parent record's definition");
609 // FIXME: all this logic will change if/when we have MemRegion::getLocation().
610 SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
611 BinaryOperator::Opcode op,
614 // Only comparisons and subtractions are valid operations on two pointers.
615 // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
616 // However, if a pointer is casted to an integer, evalBinOpNN may end up
617 // calling this function with another operation (PR7527). We don't attempt to
618 // model this for now, but it could be useful, particularly when the
619 // "location" is actually an integer value that's been passed through a void*.
620 if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
623 // Special cases for when both sides are identical.
627 llvm_unreachable("Unimplemented operation for two identical values");
629 return makeZeroVal(resultTy);
633 return makeTruthVal(true, resultTy);
637 return makeTruthVal(false, resultTy);
641 switch (lhs.getSubKind()) {
643 llvm_unreachable("Ordering not implemented for this Loc.");
645 case loc::GotoLabelKind:
646 // The only thing we know about labels is that they're non-null.
647 if (rhs.isZeroConstant()) {
652 return evalCastFromLoc(lhs, resultTy);
656 return makeTruthVal(false, resultTy);
660 return makeTruthVal(true, resultTy);
663 // There may be two labels for the same location, and a function region may
664 // have the same address as a label at the start of the function (depending
666 // FIXME: we can probably do a comparison against other MemRegions, though.
667 // FIXME: is there a way to tell if two labels refer to the same location?
670 case loc::ConcreteIntKind: {
671 // If one of the operands is a symbol and the other is a constant,
672 // build an expression for use by the constraint manager.
673 if (SymbolRef rSym = rhs.getAsLocSymbol()) {
674 // We can only build expressions with symbols on the left,
675 // so we need a reversible operator.
676 if (!BinaryOperator::isComparisonOp(op))
679 const llvm::APSInt &lVal = lhs.castAs<loc::ConcreteInt>().getValue();
680 op = BinaryOperator::reverseComparisonOp(op);
681 return makeNonLoc(rSym, op, lVal, resultTy);
684 // If both operands are constants, just perform the operation.
685 if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
687 lhs.castAs<loc::ConcreteInt>().evalBinOp(BasicVals, op, *rInt);
688 if (Optional<NonLoc> Result = ResultVal.getAs<NonLoc>())
689 return evalCastFromNonLoc(*Result, resultTy);
691 assert(!ResultVal.getAs<Loc>() && "Loc-Loc ops should not produce Locs");
695 // Special case comparisons against NULL.
696 // This must come after the test if the RHS is a symbol, which is used to
697 // build constraints. The address of any non-symbolic region is guaranteed
698 // to be non-NULL, as is any label.
699 assert(rhs.getAs<loc::MemRegionVal>() || rhs.getAs<loc::GotoLabel>());
700 if (lhs.isZeroConstant()) {
707 return makeTruthVal(false, resultTy);
711 return makeTruthVal(true, resultTy);
715 // Comparing an arbitrary integer to a region or label address is
716 // completely unknowable.
719 case loc::MemRegionValKind: {
720 if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
721 // If one of the operands is a symbol and the other is a constant,
722 // build an expression for use by the constraint manager.
723 if (SymbolRef lSym = lhs.getAsLocSymbol(true))
724 return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
726 // Special case comparisons to NULL.
727 // This must come after the test if the LHS is a symbol, which is used to
728 // build constraints. The address of any non-symbolic region is guaranteed
730 if (rInt->isZeroConstant()) {
732 return evalCastFromLoc(lhs, resultTy);
734 if (BinaryOperator::isComparisonOp(op)) {
735 QualType boolType = getContext().BoolTy;
736 NonLoc l = evalCastFromLoc(lhs, boolType).castAs<NonLoc>();
737 NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>();
738 return evalBinOpNN(state, op, l, r, resultTy);
742 // Comparing a region to an arbitrary integer is completely unknowable.
746 // Get both values as regions, if possible.
747 const MemRegion *LeftMR = lhs.getAsRegion();
748 assert(LeftMR && "MemRegionValKind SVal doesn't have a region!");
750 const MemRegion *RightMR = rhs.getAsRegion();
752 // The RHS is probably a label, which in theory could address a region.
753 // FIXME: we can probably make a more useful statement about non-code
757 const MemRegion *LeftBase = LeftMR->getBaseRegion();
758 const MemRegion *RightBase = RightMR->getBaseRegion();
759 const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
760 const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
761 const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
763 // If the two regions are from different known memory spaces they cannot be
764 // equal. Also, assume that no symbolic region (whose memory space is
765 // unknown) is on the stack.
766 if (LeftMS != RightMS &&
767 ((LeftMS != UnknownMS && RightMS != UnknownMS) ||
768 (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
773 return makeTruthVal(false, resultTy);
775 return makeTruthVal(true, resultTy);
779 // If both values wrap regions, see if they're from different base regions.
780 // Note, heap base symbolic regions are assumed to not alias with
781 // each other; for example, we assume that malloc returns different address
782 // on each invocation.
783 // FIXME: ObjC object pointers always reside on the heap, but currently
784 // we treat their memory space as unknown, because symbolic pointers
785 // to ObjC objects may alias. There should be a way to construct
786 // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker
787 // guesses memory space for ObjC object pointers manually instead of
789 if (LeftBase != RightBase &&
790 ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
791 (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
796 return makeTruthVal(false, resultTy);
798 return makeTruthVal(true, resultTy);
802 // Handle special cases for when both regions are element regions.
803 const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
804 const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR);
805 if (RightER && LeftER) {
806 // Next, see if the two ERs have the same super-region and matching types.
807 // FIXME: This should do something useful even if the types don't match,
808 // though if both indexes are constant the RegionRawOffset path will
809 // give the correct answer.
810 if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
811 LeftER->getElementType() == RightER->getElementType()) {
812 // Get the left index and cast it to the correct type.
813 // If the index is unknown or undefined, bail out here.
814 SVal LeftIndexVal = LeftER->getIndex();
815 Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
818 LeftIndexVal = evalCastFromNonLoc(*LeftIndex, ArrayIndexTy);
819 LeftIndex = LeftIndexVal.getAs<NonLoc>();
823 // Do the same for the right index.
824 SVal RightIndexVal = RightER->getIndex();
825 Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
828 RightIndexVal = evalCastFromNonLoc(*RightIndex, ArrayIndexTy);
829 RightIndex = RightIndexVal.getAs<NonLoc>();
833 // Actually perform the operation.
834 // evalBinOpNN expects the two indexes to already be the right type.
835 return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
839 // Special handling of the FieldRegions, even with symbolic offsets.
840 const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
841 const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR);
842 if (RightFR && LeftFR) {
843 SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy,
849 // Compare the regions using the raw offsets.
850 RegionOffset LeftOffset = LeftMR->getAsOffset();
851 RegionOffset RightOffset = RightMR->getAsOffset();
853 if (LeftOffset.getRegion() != nullptr &&
854 LeftOffset.getRegion() == RightOffset.getRegion() &&
855 !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) {
856 int64_t left = LeftOffset.getOffset();
857 int64_t right = RightOffset.getOffset();
863 return makeTruthVal(left < right, resultTy);
865 return makeTruthVal(left > right, resultTy);
867 return makeTruthVal(left <= right, resultTy);
869 return makeTruthVal(left >= right, resultTy);
871 return makeTruthVal(left == right, resultTy);
873 return makeTruthVal(left != right, resultTy);
877 // At this point we're not going to get a good answer, but we can try
878 // conjuring an expression instead.
879 SymbolRef LHSSym = lhs.getAsLocSymbol();
880 SymbolRef RHSSym = rhs.getAsLocSymbol();
881 if (LHSSym && RHSSym)
882 return makeNonLoc(LHSSym, op, RHSSym, resultTy);
884 // If we get here, we have no way of comparing the regions.
890 SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
891 BinaryOperator::Opcode op,
892 Loc lhs, NonLoc rhs, QualType resultTy) {
893 if (op >= BO_PtrMemD && op <= BO_PtrMemI) {
894 if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) {
895 if (PTMSV->isNullMemberPointer())
896 return UndefinedVal();
897 if (const FieldDecl *FD = PTMSV->getDeclAs<FieldDecl>()) {
900 for (const auto &I : *PTMSV)
901 Result = StateMgr.getStoreManager().evalDerivedToBase(
902 Result, I->getType(),I->isVirtual());
903 return state->getLValue(FD, Result);
910 assert(!BinaryOperator::isComparisonOp(op) &&
911 "arguments to comparison ops must be of the same type");
913 // Special case: rhs is a zero constant.
914 if (rhs.isZeroConstant())
917 // We are dealing with pointer arithmetic.
919 // Handle pointer arithmetic on constant values.
920 if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) {
921 if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) {
922 const llvm::APSInt &leftI = lhsInt->getValue();
923 assert(leftI.isUnsigned());
924 llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
926 // Convert the bitwidth of rightI. This should deal with overflow
927 // since we are dealing with concrete values.
928 rightI = rightI.extOrTrunc(leftI.getBitWidth());
930 // Offset the increment by the pointer size.
931 llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
932 rightI *= Multiplicand;
934 // Compute the adjusted pointer.
937 rightI = leftI + rightI;
940 rightI = leftI - rightI;
943 llvm_unreachable("Invalid pointer arithmetic operation");
945 return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
949 // Handle cases where 'lhs' is a region.
950 if (const MemRegion *region = lhs.getAsRegion()) {
951 rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
952 SVal index = UnknownVal();
953 const SubRegion *superR = nullptr;
954 // We need to know the type of the pointer in order to add an integer to it.
955 // Depending on the type, different amount of bytes is added.
956 QualType elementType;
958 if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
959 assert(op == BO_Add || op == BO_Sub);
960 index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
961 getArrayIndexType());
962 superR = cast<SubRegion>(elemReg->getSuperRegion());
963 elementType = elemReg->getElementType();
965 else if (isa<SubRegion>(region)) {
966 assert(op == BO_Add || op == BO_Sub);
967 index = (op == BO_Add) ? rhs : evalMinus(rhs);
968 superR = cast<SubRegion>(region);
969 // TODO: Is this actually reliable? Maybe improving our MemRegion
970 // hierarchy to provide typed regions for all non-void pointers would be
971 // better. For instance, we cannot extend this towards LocAsInteger
972 // operations, where result type of the expression is integer.
973 if (resultTy->isAnyPointerType())
974 elementType = resultTy->getPointeeType();
977 if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) {
978 return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
979 superR, getContext()));
985 const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
987 if (V.isUnknownOrUndef())
990 if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
991 return &X->getValue();
993 if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
994 return &X->getValue();
996 if (SymbolRef Sym = V.getAsSymbol())
997 return state->getConstraintManager().getSymVal(state, Sym);
999 // FIXME: Add support for SymExprs.
1003 SVal SimpleSValBuilder::simplifySVal(ProgramStateRef State, SVal V) {
1004 // For now, this function tries to constant-fold symbols inside a
1005 // nonloc::SymbolVal, and does nothing else. More simplifications should
1006 // be possible, such as constant-folding an index in an ElementRegion.
1008 class Simplifier : public FullSValVisitor<Simplifier, SVal> {
1009 ProgramStateRef State;
1013 Simplifier(ProgramStateRef State)
1014 : State(State), SVB(State->getStateManager().getSValBuilder()) {}
1016 SVal VisitSymbolData(const SymbolData *S) {
1017 if (const llvm::APSInt *I =
1018 SVB.getKnownValue(State, nonloc::SymbolVal(S)))
1019 return Loc::isLocType(S->getType()) ? (SVal)SVB.makeIntLocVal(*I)
1020 : (SVal)SVB.makeIntVal(*I);
1021 return nonloc::SymbolVal(S);
1024 // TODO: Support SymbolCast. Support IntSymExpr when/if we actually
1025 // start producing them.
1027 SVal VisitSymIntExpr(const SymIntExpr *S) {
1028 SVal LHS = Visit(S->getLHS());
1030 // By looking at the APSInt in the right-hand side of S, we cannot
1031 // figure out if it should be treated as a Loc or as a NonLoc.
1032 // So make our guess by recalling that we cannot multiply pointers
1033 // or compare a pointer to an integer.
1034 if (Loc::isLocType(S->getLHS()->getType()) &&
1035 BinaryOperator::isComparisonOp(S->getOpcode())) {
1036 // The usual conversion of $sym to &SymRegion{$sym}, as they have
1037 // the same meaning for Loc-type symbols, but the latter form
1038 // is preferred in SVal computations for being Loc itself.
1039 if (SymbolRef Sym = LHS.getAsSymbol()) {
1040 assert(Loc::isLocType(Sym->getType()));
1041 LHS = SVB.makeLoc(Sym);
1043 RHS = SVB.makeIntLocVal(S->getRHS());
1045 RHS = SVB.makeIntVal(S->getRHS());
1047 return SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType());
1050 SVal VisitSymSymExpr(const SymSymExpr *S) {
1051 SVal LHS = Visit(S->getLHS());
1052 SVal RHS = Visit(S->getRHS());
1053 return SVB.evalBinOp(State, S->getOpcode(), LHS, RHS, S->getType());
1056 SVal VisitSymExpr(SymbolRef S) { return nonloc::SymbolVal(S); }
1058 SVal VisitMemRegion(const MemRegion *R) { return loc::MemRegionVal(R); }
1060 SVal VisitNonLocSymbolVal(nonloc::SymbolVal V) {
1061 // Simplification is much more costly than computing complexity.
1062 // For high complexity, it may be not worth it.
1063 if (V.getSymbol()->computeComplexity() > 100)
1065 return Visit(V.getSymbol());
1068 SVal VisitSVal(SVal V) { return V; }
1071 return Simplifier(State).Visit(V);