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"
18 using namespace clang;
22 class SimpleSValBuilder : public SValBuilder {
24 virtual SVal dispatchCast(SVal val, QualType castTy);
25 virtual SVal evalCastFromNonLoc(NonLoc val, QualType castTy);
26 virtual SVal evalCastFromLoc(Loc val, QualType castTy);
29 SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
30 ProgramStateManager &stateMgr)
31 : SValBuilder(alloc, context, stateMgr) {}
32 virtual ~SimpleSValBuilder() {}
34 virtual SVal evalMinus(NonLoc val);
35 virtual SVal evalComplement(NonLoc val);
36 virtual SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
37 NonLoc lhs, NonLoc rhs, QualType resultTy);
38 virtual SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
39 Loc lhs, Loc rhs, QualType resultTy);
40 virtual SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
41 Loc lhs, NonLoc rhs, QualType resultTy);
43 /// getKnownValue - evaluates a given SVal. If the SVal has only one possible
44 /// (integer) value, that value is returned. Otherwise, returns NULL.
45 virtual const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V);
47 SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
48 const llvm::APSInt &RHS, QualType resultTy);
50 } // end anonymous namespace
52 SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
54 ProgramStateManager &stateMgr) {
55 return new SimpleSValBuilder(alloc, context, stateMgr);
58 //===----------------------------------------------------------------------===//
59 // Transfer function for Casts.
60 //===----------------------------------------------------------------------===//
62 SVal SimpleSValBuilder::dispatchCast(SVal Val, QualType CastTy) {
63 assert(Val.getAs<Loc>() || Val.getAs<NonLoc>());
64 return Val.getAs<Loc>() ? evalCastFromLoc(Val.castAs<Loc>(), CastTy)
65 : evalCastFromNonLoc(Val.castAs<NonLoc>(), CastTy);
68 SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
70 bool isLocType = Loc::isLocType(castTy);
72 if (Optional<nonloc::LocAsInteger> LI = val.getAs<nonloc::LocAsInteger>()) {
76 // FIXME: Correctly support promotions/truncations.
77 unsigned castSize = Context.getTypeSize(castTy);
78 if (castSize == LI->getNumBits())
80 return makeLocAsInteger(LI->getLoc(), castSize);
83 if (const SymExpr *se = val.getAsSymbolicExpression()) {
84 QualType T = Context.getCanonicalType(se->getType());
85 // If types are the same or both are integers, ignore the cast.
86 // FIXME: Remove this hack when we support symbolic truncation/extension.
87 // HACK: If both castTy and T are integers, ignore the cast. This is
88 // not a permanent solution. Eventually we want to precisely handle
89 // extension/truncation of symbolic integers. This prevents us from losing
90 // precision when we assign 'x = y' and 'y' is symbolic and x and y are
91 // different integer types.
92 if (haveSameType(T, castTy))
96 return makeNonLoc(se, T, castTy);
100 // If value is a non integer constant, produce unknown.
101 if (!val.getAs<nonloc::ConcreteInt>())
104 // Handle casts to a boolean type.
105 if (castTy->isBooleanType()) {
106 bool b = val.castAs<nonloc::ConcreteInt>().getValue().getBoolValue();
107 return makeTruthVal(b, castTy);
110 // Only handle casts from integers to integers - if val is an integer constant
111 // being cast to a non integer type, produce unknown.
112 if (!isLocType && !castTy->isIntegralOrEnumerationType())
115 llvm::APSInt i = val.castAs<nonloc::ConcreteInt>().getValue();
116 BasicVals.getAPSIntType(castTy).apply(i);
119 return makeIntLocVal(i);
121 return makeIntVal(i);
124 SVal SimpleSValBuilder::evalCastFromLoc(Loc val, QualType castTy) {
126 // Casts from pointers -> pointers, just return the lval.
128 // Casts from pointers -> references, just return the lval. These
129 // can be introduced by the frontend for corner cases, e.g
130 // casting from va_list* to __builtin_va_list&.
132 if (Loc::isLocType(castTy) || castTy->isReferenceType())
135 // FIXME: Handle transparent unions where a value can be "transparently"
136 // lifted into a union type.
137 if (castTy->isUnionType())
140 if (castTy->isIntegralOrEnumerationType()) {
141 unsigned BitWidth = Context.getTypeSize(castTy);
143 if (!val.getAs<loc::ConcreteInt>())
144 return makeLocAsInteger(val, BitWidth);
146 llvm::APSInt i = val.castAs<loc::ConcreteInt>().getValue();
147 BasicVals.getAPSIntType(castTy).apply(i);
148 return makeIntVal(i);
151 // All other cases: return 'UnknownVal'. This includes casting pointers
152 // to floats, which is probably badness it itself, but this is a good
153 // intermediate solution until we do something better.
157 //===----------------------------------------------------------------------===//
158 // Transfer function for unary operators.
159 //===----------------------------------------------------------------------===//
161 SVal SimpleSValBuilder::evalMinus(NonLoc val) {
162 switch (val.getSubKind()) {
163 case nonloc::ConcreteIntKind:
164 return val.castAs<nonloc::ConcreteInt>().evalMinus(*this);
170 SVal SimpleSValBuilder::evalComplement(NonLoc X) {
171 switch (X.getSubKind()) {
172 case nonloc::ConcreteIntKind:
173 return X.castAs<nonloc::ConcreteInt>().evalComplement(*this);
179 //===----------------------------------------------------------------------===//
180 // Transfer function for binary operators.
181 //===----------------------------------------------------------------------===//
183 SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
184 BinaryOperator::Opcode op,
185 const llvm::APSInt &RHS,
187 bool isIdempotent = false;
189 // Check for a few special cases with known reductions first.
192 // We can't reduce this case; just treat it normally.
197 return makeIntVal(0, resultTy);
204 // This is also handled elsewhere.
205 return UndefinedVal();
212 // This is also handled elsewhere.
213 return UndefinedVal();
215 return makeIntVal(0, resultTy);
222 // a+0, a-0, a<<0, a>>0, a^0
229 return makeIntVal(0, resultTy);
230 else if (RHS.isAllOnesValue())
237 else if (RHS.isAllOnesValue()) {
238 const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
239 return nonloc::ConcreteInt(Result);
244 // Idempotent ops (like a*1) can still change the type of an expression.
245 // Wrap the LHS up in a NonLoc again and let evalCastFromNonLoc do the
248 return evalCastFromNonLoc(nonloc::SymbolVal(LHS), resultTy);
250 // If we reach this point, the expression cannot be simplified.
251 // Make a SymbolVal for the entire expression, after converting the RHS.
252 const llvm::APSInt *ConvertedRHS = &RHS;
253 if (BinaryOperator::isComparisonOp(op)) {
254 // We're looking for a type big enough to compare the symbolic value
255 // with the given constant.
256 // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
257 ASTContext &Ctx = getContext();
258 QualType SymbolType = LHS->getType();
259 uint64_t ValWidth = RHS.getBitWidth();
260 uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
262 if (ValWidth < TypeWidth) {
263 // If the value is too small, extend it.
264 ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
265 } else if (ValWidth == TypeWidth) {
266 // If the value is signed but the symbol is unsigned, do the comparison
267 // in unsigned space. [C99 6.3.1.8]
268 // (For the opposite case, the value is already unsigned.)
269 if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
270 ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
273 ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
275 return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
278 SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
279 BinaryOperator::Opcode op,
280 NonLoc lhs, NonLoc rhs,
282 NonLoc InputLHS = lhs;
283 NonLoc InputRHS = rhs;
285 // Handle trivial case where left-side and right-side are the same.
293 return makeTruthVal(true, resultTy);
297 return makeTruthVal(false, resultTy);
300 if (resultTy->isIntegralOrEnumerationType())
301 return makeIntVal(0, resultTy);
302 return evalCastFromNonLoc(makeIntVal(0, /*Unsigned=*/false), resultTy);
305 return evalCastFromNonLoc(lhs, resultTy);
309 switch (lhs.getSubKind()) {
311 return makeSymExprValNN(state, op, lhs, rhs, resultTy);
312 case nonloc::LocAsIntegerKind: {
313 Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc();
314 switch (rhs.getSubKind()) {
315 case nonloc::LocAsIntegerKind:
316 return evalBinOpLL(state, op, lhsL,
317 rhs.castAs<nonloc::LocAsInteger>().getLoc(),
319 case nonloc::ConcreteIntKind: {
320 // Transform the integer into a location and compare.
321 llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue();
322 BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
323 return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
328 return makeTruthVal(false, resultTy);
330 return makeTruthVal(true, resultTy);
332 // This case also handles pointer arithmetic.
333 return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
337 case nonloc::ConcreteIntKind: {
338 llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
340 // If we're dealing with two known constants, just perform the operation.
341 if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) {
342 llvm::APSInt RHSValue = *KnownRHSValue;
343 if (BinaryOperator::isComparisonOp(op)) {
344 // We're looking for a type big enough to compare the two values.
345 // FIXME: This is not correct. char + short will result in a promotion
346 // to int. Unfortunately we have lost types by this point.
347 APSIntType CompareType = std::max(APSIntType(LHSValue),
348 APSIntType(RHSValue));
349 CompareType.apply(LHSValue);
350 CompareType.apply(RHSValue);
351 } else if (!BinaryOperator::isShiftOp(op)) {
352 APSIntType IntType = BasicVals.getAPSIntType(resultTy);
353 IntType.apply(LHSValue);
354 IntType.apply(RHSValue);
357 const llvm::APSInt *Result =
358 BasicVals.evalAPSInt(op, LHSValue, RHSValue);
360 return UndefinedVal();
362 return nonloc::ConcreteInt(*Result);
365 // Swap the left and right sides and flip the operator if doing so
366 // allows us to better reason about the expression (this is a form
367 // of expression canonicalization).
368 // While we're at it, catch some special cases for non-commutative ops.
374 op = BinaryOperator::reverseComparisonOp(op);
387 if (LHSValue.isAllOnesValue() && LHSValue.isSigned())
388 return evalCastFromNonLoc(lhs, resultTy);
393 return evalCastFromNonLoc(lhs, resultTy);
394 return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
396 return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
399 case nonloc::SymbolValKind: {
400 // We only handle LHS as simple symbols or SymIntExprs.
401 SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
403 // LHS is a symbolic expression.
404 if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
406 // Is this a logical not? (!x is represented as x == 0.)
407 if (op == BO_EQ && rhs.isZeroConstant()) {
408 // We know how to negate certain expressions. Simplify them here.
410 BinaryOperator::Opcode opc = symIntExpr->getOpcode();
413 // We don't know how to negate this operation.
414 // Just handle it as if it were a normal comparison to 0.
418 llvm_unreachable("Logical operators handled by branching logic.");
431 llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
434 llvm_unreachable("Pointer arithmetic not handled here.");
441 assert(resultTy->isBooleanType() ||
442 resultTy == getConditionType());
443 assert(symIntExpr->getType()->isBooleanType() ||
444 getContext().hasSameUnqualifiedType(symIntExpr->getType(),
445 getConditionType()));
446 // Negate the comparison and make a value.
447 opc = BinaryOperator::negateComparisonOp(opc);
448 return makeNonLoc(symIntExpr->getLHS(), opc,
449 symIntExpr->getRHS(), resultTy);
453 // For now, only handle expressions whose RHS is a constant.
454 if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) {
455 // If both the LHS and the current expression are additive,
456 // fold their constants and try again.
457 if (BinaryOperator::isAdditiveOp(op)) {
458 BinaryOperator::Opcode lop = symIntExpr->getOpcode();
459 if (BinaryOperator::isAdditiveOp(lop)) {
460 // Convert the two constants to a common type, then combine them.
462 // resultTy may not be the best type to convert to, but it's
463 // probably the best choice in expressions with mixed type
464 // (such as x+1U+2LL). The rules for implicit conversions should
465 // choose a reasonable type to preserve the expression, and will
466 // at least match how the value is going to be used.
467 APSIntType IntType = BasicVals.getAPSIntType(resultTy);
468 const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
469 const llvm::APSInt &second = IntType.convert(*RHSValue);
471 const llvm::APSInt *newRHS;
473 newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
475 newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
477 assert(newRHS && "Invalid operation despite common type!");
478 rhs = nonloc::ConcreteInt(*newRHS);
479 lhs = nonloc::SymbolVal(symIntExpr->getLHS());
485 // Otherwise, make a SymIntExpr out of the expression.
486 return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
490 // Does the symbolic expression simplify to a constant?
491 // If so, "fold" the constant by setting 'lhs' to a ConcreteInt
493 ConstraintManager &CMgr = state->getConstraintManager();
494 if (const llvm::APSInt *Constant = CMgr.getSymVal(state, Sym)) {
495 lhs = nonloc::ConcreteInt(*Constant);
499 // Is the RHS a constant?
500 if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
501 return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
503 // Give up -- this is not a symbolic expression we can handle.
504 return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
510 // FIXME: all this logic will change if/when we have MemRegion::getLocation().
511 SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
512 BinaryOperator::Opcode op,
515 // Only comparisons and subtractions are valid operations on two pointers.
516 // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
517 // However, if a pointer is casted to an integer, evalBinOpNN may end up
518 // calling this function with another operation (PR7527). We don't attempt to
519 // model this for now, but it could be useful, particularly when the
520 // "location" is actually an integer value that's been passed through a void*.
521 if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
524 // Special cases for when both sides are identical.
528 llvm_unreachable("Unimplemented operation for two identical values");
530 return makeZeroVal(resultTy);
534 return makeTruthVal(true, resultTy);
538 return makeTruthVal(false, resultTy);
542 switch (lhs.getSubKind()) {
544 llvm_unreachable("Ordering not implemented for this Loc.");
546 case loc::GotoLabelKind:
547 // The only thing we know about labels is that they're non-null.
548 if (rhs.isZeroConstant()) {
553 return evalCastFromLoc(lhs, resultTy);
557 return makeTruthVal(false, resultTy);
561 return makeTruthVal(true, resultTy);
564 // There may be two labels for the same location, and a function region may
565 // have the same address as a label at the start of the function (depending
567 // FIXME: we can probably do a comparison against other MemRegions, though.
568 // FIXME: is there a way to tell if two labels refer to the same location?
571 case loc::ConcreteIntKind: {
572 // If one of the operands is a symbol and the other is a constant,
573 // build an expression for use by the constraint manager.
574 if (SymbolRef rSym = rhs.getAsLocSymbol()) {
575 // We can only build expressions with symbols on the left,
576 // so we need a reversible operator.
577 if (!BinaryOperator::isComparisonOp(op))
580 const llvm::APSInt &lVal = lhs.castAs<loc::ConcreteInt>().getValue();
581 op = BinaryOperator::reverseComparisonOp(op);
582 return makeNonLoc(rSym, op, lVal, resultTy);
585 // If both operands are constants, just perform the operation.
586 if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
588 lhs.castAs<loc::ConcreteInt>().evalBinOp(BasicVals, op, *rInt);
589 if (Optional<NonLoc> Result = ResultVal.getAs<NonLoc>())
590 return evalCastFromNonLoc(*Result, resultTy);
592 assert(!ResultVal.getAs<Loc>() && "Loc-Loc ops should not produce Locs");
596 // Special case comparisons against NULL.
597 // This must come after the test if the RHS is a symbol, which is used to
598 // build constraints. The address of any non-symbolic region is guaranteed
599 // to be non-NULL, as is any label.
600 assert(rhs.getAs<loc::MemRegionVal>() || rhs.getAs<loc::GotoLabel>());
601 if (lhs.isZeroConstant()) {
608 return makeTruthVal(false, resultTy);
612 return makeTruthVal(true, resultTy);
616 // Comparing an arbitrary integer to a region or label address is
617 // completely unknowable.
620 case loc::MemRegionKind: {
621 if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
622 // If one of the operands is a symbol and the other is a constant,
623 // build an expression for use by the constraint manager.
624 if (SymbolRef lSym = lhs.getAsLocSymbol())
625 return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
627 // Special case comparisons to NULL.
628 // This must come after the test if the LHS is a symbol, which is used to
629 // build constraints. The address of any non-symbolic region is guaranteed
631 if (rInt->isZeroConstant()) {
636 return evalCastFromLoc(lhs, resultTy);
640 return makeTruthVal(false, resultTy);
644 return makeTruthVal(true, resultTy);
648 // Comparing a region to an arbitrary integer is completely unknowable.
652 // Get both values as regions, if possible.
653 const MemRegion *LeftMR = lhs.getAsRegion();
654 assert(LeftMR && "MemRegionKind SVal doesn't have a region!");
656 const MemRegion *RightMR = rhs.getAsRegion();
658 // The RHS is probably a label, which in theory could address a region.
659 // FIXME: we can probably make a more useful statement about non-code
663 const MemRegion *LeftBase = LeftMR->getBaseRegion();
664 const MemRegion *RightBase = RightMR->getBaseRegion();
665 const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
666 const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
667 const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
669 // If the two regions are from different known memory spaces they cannot be
670 // equal. Also, assume that no symbolic region (whose memory space is
671 // unknown) is on the stack.
672 if (LeftMS != RightMS &&
673 ((LeftMS != UnknownMS && RightMS != UnknownMS) ||
674 (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
679 return makeTruthVal(false, resultTy);
681 return makeTruthVal(true, resultTy);
685 // If both values wrap regions, see if they're from different base regions.
686 // Note, heap base symbolic regions are assumed to not alias with
687 // each other; for example, we assume that malloc returns different address
688 // on each invocation.
689 if (LeftBase != RightBase &&
690 ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
691 (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
696 return makeTruthVal(false, resultTy);
698 return makeTruthVal(true, resultTy);
702 // FIXME: If/when there is a getAsRawOffset() for FieldRegions, this
703 // ElementRegion path and the FieldRegion path below should be unified.
704 if (const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR)) {
705 // First see if the right region is also an ElementRegion.
706 const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
710 // Next, see if the two ERs have the same super-region and matching types.
711 // FIXME: This should do something useful even if the types don't match,
712 // though if both indexes are constant the RegionRawOffset path will
713 // give the correct answer.
714 if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
715 LeftER->getElementType() == RightER->getElementType()) {
716 // Get the left index and cast it to the correct type.
717 // If the index is unknown or undefined, bail out here.
718 SVal LeftIndexVal = LeftER->getIndex();
719 Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
722 LeftIndexVal = evalCastFromNonLoc(*LeftIndex, ArrayIndexTy);
723 LeftIndex = LeftIndexVal.getAs<NonLoc>();
727 // Do the same for the right index.
728 SVal RightIndexVal = RightER->getIndex();
729 Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
732 RightIndexVal = evalCastFromNonLoc(*RightIndex, ArrayIndexTy);
733 RightIndex = RightIndexVal.getAs<NonLoc>();
737 // Actually perform the operation.
738 // evalBinOpNN expects the two indexes to already be the right type.
739 return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
742 // If the element indexes aren't comparable, see if the raw offsets are.
743 RegionRawOffset LeftOffset = LeftER->getAsArrayOffset();
744 RegionRawOffset RightOffset = RightER->getAsArrayOffset();
746 if (LeftOffset.getRegion() != NULL &&
747 LeftOffset.getRegion() == RightOffset.getRegion()) {
748 CharUnits left = LeftOffset.getOffset();
749 CharUnits right = RightOffset.getOffset();
755 return makeTruthVal(left < right, resultTy);
757 return makeTruthVal(left > right, resultTy);
759 return makeTruthVal(left <= right, resultTy);
761 return makeTruthVal(left >= right, resultTy);
763 return makeTruthVal(left == right, resultTy);
765 return makeTruthVal(left != right, resultTy);
769 // If we get here, we have no way of comparing the ElementRegions.
772 // See if both regions are fields of the same structure.
773 // FIXME: This doesn't handle nesting, inheritance, or Objective-C ivars.
774 if (const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR)) {
775 // Only comparisons are meaningful here!
776 if (!BinaryOperator::isComparisonOp(op))
779 // First see if the right region is also a FieldRegion.
780 const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
784 // Next, see if the two FRs have the same super-region.
785 // FIXME: This doesn't handle casts yet, and simply stripping the casts
787 if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
790 const FieldDecl *LeftFD = LeftFR->getDecl();
791 const FieldDecl *RightFD = RightFR->getDecl();
792 const RecordDecl *RD = LeftFD->getParent();
794 // Make sure the two FRs are from the same kind of record. Just in case!
795 // FIXME: This is probably where inheritance would be a problem.
796 if (RD != RightFD->getParent())
799 // We know for sure that the two fields are not the same, since that
800 // would have given us the same SVal.
802 return makeTruthVal(false, resultTy);
804 return makeTruthVal(true, resultTy);
806 // Iterate through the fields and see which one comes first.
807 // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
808 // members and the units in which bit-fields reside have addresses that
809 // increase in the order in which they are declared."
810 bool leftFirst = (op == BO_LT || op == BO_LE);
811 for (RecordDecl::field_iterator I = RD->field_begin(),
812 E = RD->field_end(); I!=E; ++I) {
814 return makeTruthVal(leftFirst, resultTy);
816 return makeTruthVal(!leftFirst, resultTy);
819 llvm_unreachable("Fields not found in parent record's definition");
822 // At this point we're not going to get a good answer, but we can try
823 // conjuring an expression instead.
824 SymbolRef LHSSym = lhs.getAsLocSymbol();
825 SymbolRef RHSSym = rhs.getAsLocSymbol();
826 if (LHSSym && RHSSym)
827 return makeNonLoc(LHSSym, op, RHSSym, resultTy);
829 // If we get here, we have no way of comparing the regions.
835 SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
836 BinaryOperator::Opcode op,
837 Loc lhs, NonLoc rhs, QualType resultTy) {
839 // Special case: rhs is a zero constant.
840 if (rhs.isZeroConstant())
843 // Special case: 'rhs' is an integer that has the same width as a pointer and
844 // we are using the integer location in a comparison. Normally this cannot be
845 // triggered, but transfer functions like those for OSCompareAndSwapBarrier32
846 // can generate comparisons that trigger this code.
847 // FIXME: Are all locations guaranteed to have pointer width?
848 if (BinaryOperator::isComparisonOp(op)) {
849 if (Optional<nonloc::ConcreteInt> rhsInt =
850 rhs.getAs<nonloc::ConcreteInt>()) {
851 const llvm::APSInt *x = &rhsInt->getValue();
852 ASTContext &ctx = Context;
853 if (ctx.getTypeSize(ctx.VoidPtrTy) == x->getBitWidth()) {
854 // Convert the signedness of the integer (if necessary).
856 x = &getBasicValueFactory().getValue(*x, true);
858 return evalBinOpLL(state, op, lhs, loc::ConcreteInt(*x), resultTy);
864 // We are dealing with pointer arithmetic.
866 // Handle pointer arithmetic on constant values.
867 if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) {
868 if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) {
869 const llvm::APSInt &leftI = lhsInt->getValue();
870 assert(leftI.isUnsigned());
871 llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
873 // Convert the bitwidth of rightI. This should deal with overflow
874 // since we are dealing with concrete values.
875 rightI = rightI.extOrTrunc(leftI.getBitWidth());
877 // Offset the increment by the pointer size.
878 llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
879 rightI *= Multiplicand;
881 // Compute the adjusted pointer.
884 rightI = leftI + rightI;
887 rightI = leftI - rightI;
890 llvm_unreachable("Invalid pointer arithmetic operation");
892 return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
896 // Handle cases where 'lhs' is a region.
897 if (const MemRegion *region = lhs.getAsRegion()) {
898 rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
899 SVal index = UnknownVal();
900 const MemRegion *superR = 0;
901 QualType elementType;
903 if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
904 assert(op == BO_Add || op == BO_Sub);
905 index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
906 getArrayIndexType());
907 superR = elemReg->getSuperRegion();
908 elementType = elemReg->getElementType();
910 else if (isa<SubRegion>(region)) {
913 if (resultTy->isAnyPointerType())
914 elementType = resultTy->getPointeeType();
917 if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) {
918 return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
919 superR, getContext()));
925 const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
927 if (V.isUnknownOrUndef())
930 if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
931 return &X->getValue();
933 if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
934 return &X->getValue();
936 if (SymbolRef Sym = V.getAsSymbol())
937 return state->getConstraintManager().getSymVal(state, Sym);
939 // FIXME: Add support for SymExprs.