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/GRState.h"
17 using namespace clang;
21 class SimpleSValBuilder : public SValBuilder {
23 virtual SVal evalCastFromNonLoc(NonLoc val, QualType castTy);
24 virtual SVal evalCastFromLoc(Loc val, QualType castTy);
27 SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
28 GRStateManager &stateMgr)
29 : SValBuilder(alloc, context, stateMgr) {}
30 virtual ~SimpleSValBuilder() {}
32 virtual SVal evalMinus(NonLoc val);
33 virtual SVal evalComplement(NonLoc val);
34 virtual SVal evalBinOpNN(const GRState *state, BinaryOperator::Opcode op,
35 NonLoc lhs, NonLoc rhs, QualType resultTy);
36 virtual SVal evalBinOpLL(const GRState *state, BinaryOperator::Opcode op,
37 Loc lhs, Loc rhs, QualType resultTy);
38 virtual SVal evalBinOpLN(const GRState *state, BinaryOperator::Opcode op,
39 Loc lhs, NonLoc rhs, QualType resultTy);
41 /// getKnownValue - evaluates a given SVal. If the SVal has only one possible
42 /// (integer) value, that value is returned. Otherwise, returns NULL.
43 virtual const llvm::APSInt *getKnownValue(const GRState *state, SVal V);
45 SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
46 const llvm::APSInt &RHS, QualType resultTy);
48 } // end anonymous namespace
50 SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
52 GRStateManager &stateMgr) {
53 return new SimpleSValBuilder(alloc, context, stateMgr);
56 //===----------------------------------------------------------------------===//
57 // Transfer function for Casts.
58 //===----------------------------------------------------------------------===//
60 SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
62 bool isLocType = Loc::isLocType(castTy);
64 if (nonloc::LocAsInteger *LI = dyn_cast<nonloc::LocAsInteger>(&val)) {
68 // FIXME: Correctly support promotions/truncations.
69 unsigned castSize = Context.getTypeSize(castTy);
70 if (castSize == LI->getNumBits())
72 return makeLocAsInteger(LI->getLoc(), castSize);
75 if (const SymExpr *se = val.getAsSymbolicExpression()) {
76 QualType T = Context.getCanonicalType(se->getType(Context));
77 if (T == Context.getCanonicalType(castTy))
80 // FIXME: Remove this hack when we support symbolic truncation/extension.
81 // HACK: If both castTy and T are integers, ignore the cast. This is
82 // not a permanent solution. Eventually we want to precisely handle
83 // extension/truncation of symbolic integers. This prevents us from losing
84 // precision when we assign 'x = y' and 'y' is symbolic and x and y are
85 // different integer types.
86 if (T->isIntegerType() && castTy->isIntegerType())
92 if (!isa<nonloc::ConcreteInt>(val))
95 // Only handle casts from integers to integers.
96 if (!isLocType && !castTy->isIntegerType())
99 llvm::APSInt i = cast<nonloc::ConcreteInt>(val).getValue();
100 i.setIsUnsigned(castTy->isUnsignedIntegerOrEnumerationType() ||
101 Loc::isLocType(castTy));
102 i = i.extOrTrunc(Context.getTypeSize(castTy));
105 return makeIntLocVal(i);
107 return makeIntVal(i);
110 SVal SimpleSValBuilder::evalCastFromLoc(Loc val, QualType castTy) {
112 // Casts from pointers -> pointers, just return the lval.
114 // Casts from pointers -> references, just return the lval. These
115 // can be introduced by the frontend for corner cases, e.g
116 // casting from va_list* to __builtin_va_list&.
118 if (Loc::isLocType(castTy) || castTy->isReferenceType())
121 // FIXME: Handle transparent unions where a value can be "transparently"
122 // lifted into a union type.
123 if (castTy->isUnionType())
126 if (castTy->isIntegerType()) {
127 unsigned BitWidth = Context.getTypeSize(castTy);
129 if (!isa<loc::ConcreteInt>(val))
130 return makeLocAsInteger(val, BitWidth);
132 llvm::APSInt i = cast<loc::ConcreteInt>(val).getValue();
133 i.setIsUnsigned(castTy->isUnsignedIntegerOrEnumerationType() ||
134 Loc::isLocType(castTy));
135 i = i.extOrTrunc(BitWidth);
136 return makeIntVal(i);
139 // All other cases: return 'UnknownVal'. This includes casting pointers
140 // to floats, which is probably badness it itself, but this is a good
141 // intermediate solution until we do something better.
145 //===----------------------------------------------------------------------===//
146 // Transfer function for unary operators.
147 //===----------------------------------------------------------------------===//
149 SVal SimpleSValBuilder::evalMinus(NonLoc val) {
150 switch (val.getSubKind()) {
151 case nonloc::ConcreteIntKind:
152 return cast<nonloc::ConcreteInt>(val).evalMinus(*this);
158 SVal SimpleSValBuilder::evalComplement(NonLoc X) {
159 switch (X.getSubKind()) {
160 case nonloc::ConcreteIntKind:
161 return cast<nonloc::ConcreteInt>(X).evalComplement(*this);
167 //===----------------------------------------------------------------------===//
168 // Transfer function for binary operators.
169 //===----------------------------------------------------------------------===//
171 static BinaryOperator::Opcode NegateComparison(BinaryOperator::Opcode op) {
174 assert(false && "Invalid opcode.");
175 case BO_LT: return BO_GE;
176 case BO_GT: return BO_LE;
177 case BO_LE: return BO_GT;
178 case BO_GE: return BO_LT;
179 case BO_EQ: return BO_NE;
180 case BO_NE: return BO_EQ;
184 static BinaryOperator::Opcode ReverseComparison(BinaryOperator::Opcode op) {
187 assert(false && "Invalid opcode.");
188 case BO_LT: return BO_GT;
189 case BO_GT: return BO_LT;
190 case BO_LE: return BO_GE;
191 case BO_GE: return BO_LE;
198 SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
199 BinaryOperator::Opcode op,
200 const llvm::APSInt &RHS,
202 bool isIdempotent = false;
204 // Check for a few special cases with known reductions first.
207 // We can't reduce this case; just treat it normally.
212 return makeIntVal(0, resultTy);
219 // This is also handled elsewhere.
220 return UndefinedVal();
227 // This is also handled elsewhere.
228 return UndefinedVal();
230 return makeIntVal(0, resultTy);
237 // a+0, a-0, a<<0, a>>0, a^0
244 return makeIntVal(0, resultTy);
245 else if (RHS.isAllOnesValue())
252 else if (RHS.isAllOnesValue()) {
253 const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
254 return nonloc::ConcreteInt(Result);
259 // Idempotent ops (like a*1) can still change the type of an expression.
260 // Wrap the LHS up in a NonLoc again and let evalCastFromNonLoc do the
263 if (SymbolRef LHSSym = dyn_cast<SymbolData>(LHS))
264 return evalCastFromNonLoc(nonloc::SymbolVal(LHSSym), resultTy);
265 return evalCastFromNonLoc(nonloc::SymExprVal(LHS), resultTy);
268 // If we reach this point, the expression cannot be simplified.
269 // Make a SymExprVal for the entire thing.
270 return makeNonLoc(LHS, op, RHS, resultTy);
273 SVal SimpleSValBuilder::evalBinOpNN(const GRState *state,
274 BinaryOperator::Opcode op,
275 NonLoc lhs, NonLoc rhs,
277 // Handle trivial case where left-side and right-side are the same.
285 return makeTruthVal(true, resultTy);
289 return makeTruthVal(false, resultTy);
292 return makeIntVal(0, resultTy);
295 return evalCastFromNonLoc(lhs, resultTy);
299 switch (lhs.getSubKind()) {
302 case nonloc::LocAsIntegerKind: {
303 Loc lhsL = cast<nonloc::LocAsInteger>(lhs).getLoc();
304 switch (rhs.getSubKind()) {
305 case nonloc::LocAsIntegerKind:
306 return evalBinOpLL(state, op, lhsL,
307 cast<nonloc::LocAsInteger>(rhs).getLoc(),
309 case nonloc::ConcreteIntKind: {
310 // Transform the integer into a location and compare.
311 llvm::APSInt i = cast<nonloc::ConcreteInt>(rhs).getValue();
312 i.setIsUnsigned(true);
313 i = i.extOrTrunc(Context.getTypeSize(Context.VoidPtrTy));
314 return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
319 return makeTruthVal(false, resultTy);
321 return makeTruthVal(true, resultTy);
323 // This case also handles pointer arithmetic.
328 case nonloc::SymExprValKind: {
329 nonloc::SymExprVal *selhs = cast<nonloc::SymExprVal>(&lhs);
331 // Only handle LHS of the form "$sym op constant", at least for now.
332 const SymIntExpr *symIntExpr =
333 dyn_cast<SymIntExpr>(selhs->getSymbolicExpression());
338 // Is this a logical not? (!x is represented as x == 0.)
339 if (op == BO_EQ && rhs.isZeroConstant()) {
340 // We know how to negate certain expressions. Simplify them here.
342 BinaryOperator::Opcode opc = symIntExpr->getOpcode();
345 // We don't know how to negate this operation.
346 // Just handle it as if it were a normal comparison to 0.
350 assert(false && "Logical operators handled by branching logic.");
364 assert(false && "'=' and ',' operators handled by ExprEngine.");
368 assert(false && "Pointer arithmetic not handled here.");
376 // Negate the comparison and make a value.
377 opc = NegateComparison(opc);
378 assert(symIntExpr->getType(Context) == resultTy);
379 return makeNonLoc(symIntExpr->getLHS(), opc,
380 symIntExpr->getRHS(), resultTy);
384 // For now, only handle expressions whose RHS is a constant.
385 const nonloc::ConcreteInt *rhsInt = dyn_cast<nonloc::ConcreteInt>(&rhs);
389 // If both the LHS and the current expression are additive,
390 // fold their constants.
391 if (BinaryOperator::isAdditiveOp(op)) {
392 BinaryOperator::Opcode lop = symIntExpr->getOpcode();
393 if (BinaryOperator::isAdditiveOp(lop)) {
394 // resultTy may not be the best type to convert to, but it's
395 // probably the best choice in expressions with mixed type
396 // (such as x+1U+2LL). The rules for implicit conversions should
397 // choose a reasonable type to preserve the expression, and will
398 // at least match how the value is going to be used.
399 const llvm::APSInt &first =
400 BasicVals.Convert(resultTy, symIntExpr->getRHS());
401 const llvm::APSInt &second =
402 BasicVals.Convert(resultTy, rhsInt->getValue());
403 const llvm::APSInt *newRHS;
405 newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
407 newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
408 return MakeSymIntVal(symIntExpr->getLHS(), lop, *newRHS, resultTy);
412 // Otherwise, make a SymExprVal out of the expression.
413 return MakeSymIntVal(symIntExpr, op, rhsInt->getValue(), resultTy);
415 case nonloc::ConcreteIntKind: {
416 const nonloc::ConcreteInt& lhsInt = cast<nonloc::ConcreteInt>(lhs);
418 // Is the RHS a symbol we can simplify?
419 // FIXME: This was mostly copy/pasted from the LHS-is-a-symbol case.
420 if (const nonloc::SymbolVal *srhs = dyn_cast<nonloc::SymbolVal>(&rhs)) {
421 SymbolRef RSym = srhs->getSymbol();
422 if (RSym->getType(Context)->isIntegerType()) {
423 if (const llvm::APSInt *Constant = state->getSymVal(RSym)) {
424 // The symbol evaluates to a constant.
425 const llvm::APSInt *rhs_I;
426 if (BinaryOperator::isRelationalOp(op))
427 rhs_I = &BasicVals.Convert(lhsInt.getValue(), *Constant);
429 rhs_I = &BasicVals.Convert(resultTy, *Constant);
431 rhs = nonloc::ConcreteInt(*rhs_I);
436 if (isa<nonloc::ConcreteInt>(rhs)) {
437 return lhsInt.evalBinOp(*this, op, cast<nonloc::ConcreteInt>(rhs));
439 const llvm::APSInt& lhsValue = lhsInt.getValue();
441 // Swap the left and right sides and flip the operator if doing so
442 // allows us to better reason about the expression (this is a form
443 // of expression canonicalization).
444 // While we're at it, catch some special cases for non-commutative ops.
454 op = ReverseComparison(op);
465 if (lhsValue.isAllOnesValue() && lhsValue.isSigned())
466 // At this point lhs and rhs have been swapped.
471 // At this point lhs and rhs have been swapped.
479 case nonloc::SymbolValKind: {
480 nonloc::SymbolVal *slhs = cast<nonloc::SymbolVal>(&lhs);
481 SymbolRef Sym = slhs->getSymbol();
482 QualType lhsType = Sym->getType(Context);
484 // The conversion type is usually the result type, but not in the case
485 // of relational expressions.
486 QualType conversionType = resultTy;
487 if (BinaryOperator::isRelationalOp(op))
488 conversionType = lhsType;
490 // Does the symbol simplify to a constant? If so, "fold" the constant
491 // by setting 'lhs' to a ConcreteInt and try again.
492 if (lhsType->isIntegerType())
493 if (const llvm::APSInt *Constant = state->getSymVal(Sym)) {
494 // The symbol evaluates to a constant. If necessary, promote the
495 // folded constant (LHS) to the result type.
496 const llvm::APSInt &lhs_I = BasicVals.Convert(conversionType,
498 lhs = nonloc::ConcreteInt(lhs_I);
500 // Also promote the RHS (if necessary).
502 // For shifts, it is not necessary to promote the RHS.
503 if (BinaryOperator::isShiftOp(op))
506 // Other operators: do an implicit conversion. This shouldn't be
507 // necessary once we support truncation/extension of symbolic values.
508 if (nonloc::ConcreteInt *rhs_I = dyn_cast<nonloc::ConcreteInt>(&rhs)){
509 rhs = nonloc::ConcreteInt(BasicVals.Convert(conversionType,
516 // Is the RHS a symbol we can simplify?
517 if (const nonloc::SymbolVal *srhs = dyn_cast<nonloc::SymbolVal>(&rhs)) {
518 SymbolRef RSym = srhs->getSymbol();
519 if (RSym->getType(Context)->isIntegerType()) {
520 if (const llvm::APSInt *Constant = state->getSymVal(RSym)) {
521 // The symbol evaluates to a constant.
522 const llvm::APSInt &rhs_I = BasicVals.Convert(conversionType,
524 rhs = nonloc::ConcreteInt(rhs_I);
529 if (isa<nonloc::ConcreteInt>(rhs)) {
530 return MakeSymIntVal(slhs->getSymbol(), op,
531 cast<nonloc::ConcreteInt>(rhs).getValue(),
541 // FIXME: all this logic will change if/when we have MemRegion::getLocation().
542 SVal SimpleSValBuilder::evalBinOpLL(const GRState *state,
543 BinaryOperator::Opcode op,
546 // Only comparisons and subtractions are valid operations on two pointers.
547 // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
548 // However, if a pointer is casted to an integer, evalBinOpNN may end up
549 // calling this function with another operation (PR7527). We don't attempt to
550 // model this for now, but it could be useful, particularly when the
551 // "location" is actually an integer value that's been passed through a void*.
552 if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
555 // Special cases for when both sides are identical.
559 assert(false && "Unimplemented operation for two identical values");
562 return makeZeroVal(resultTy);
566 return makeTruthVal(true, resultTy);
570 return makeTruthVal(false, resultTy);
574 switch (lhs.getSubKind()) {
576 assert(false && "Ordering not implemented for this Loc.");
579 case loc::GotoLabelKind:
580 // The only thing we know about labels is that they're non-null.
581 if (rhs.isZeroConstant()) {
586 return evalCastFromLoc(lhs, resultTy);
590 return makeTruthVal(false, resultTy);
594 return makeTruthVal(true, resultTy);
597 // There may be two labels for the same location, and a function region may
598 // have the same address as a label at the start of the function (depending
600 // FIXME: we can probably do a comparison against other MemRegions, though.
601 // FIXME: is there a way to tell if two labels refer to the same location?
604 case loc::ConcreteIntKind: {
605 // If one of the operands is a symbol and the other is a constant,
606 // build an expression for use by the constraint manager.
607 if (SymbolRef rSym = rhs.getAsLocSymbol()) {
608 // We can only build expressions with symbols on the left,
609 // so we need a reversible operator.
610 if (!BinaryOperator::isComparisonOp(op))
613 const llvm::APSInt &lVal = cast<loc::ConcreteInt>(lhs).getValue();
614 return makeNonLoc(rSym, ReverseComparison(op), lVal, resultTy);
617 // If both operands are constants, just perform the operation.
618 if (loc::ConcreteInt *rInt = dyn_cast<loc::ConcreteInt>(&rhs)) {
619 SVal ResultVal = cast<loc::ConcreteInt>(lhs).evalBinOp(BasicVals, op,
621 if (Loc *Result = dyn_cast<Loc>(&ResultVal))
622 return evalCastFromLoc(*Result, resultTy);
627 // Special case comparisons against NULL.
628 // This must come after the test if the RHS is a symbol, which is used to
629 // build constraints. The address of any non-symbolic region is guaranteed
630 // to be non-NULL, as is any label.
631 assert(isa<loc::MemRegionVal>(rhs) || isa<loc::GotoLabel>(rhs));
632 if (lhs.isZeroConstant()) {
639 return makeTruthVal(false, resultTy);
643 return makeTruthVal(true, resultTy);
647 // Comparing an arbitrary integer to a region or label address is
648 // completely unknowable.
651 case loc::MemRegionKind: {
652 if (loc::ConcreteInt *rInt = dyn_cast<loc::ConcreteInt>(&rhs)) {
653 // If one of the operands is a symbol and the other is a constant,
654 // build an expression for use by the constraint manager.
655 if (SymbolRef lSym = lhs.getAsLocSymbol())
656 return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
658 // Special case comparisons to NULL.
659 // This must come after the test if the LHS is a symbol, which is used to
660 // build constraints. The address of any non-symbolic region is guaranteed
662 if (rInt->isZeroConstant()) {
667 return evalCastFromLoc(lhs, resultTy);
671 return makeTruthVal(false, resultTy);
675 return makeTruthVal(true, resultTy);
679 // Comparing a region to an arbitrary integer is completely unknowable.
683 // Get both values as regions, if possible.
684 const MemRegion *LeftMR = lhs.getAsRegion();
685 assert(LeftMR && "MemRegionKind SVal doesn't have a region!");
687 const MemRegion *RightMR = rhs.getAsRegion();
689 // The RHS is probably a label, which in theory could address a region.
690 // FIXME: we can probably make a more useful statement about non-code
694 // If both values wrap regions, see if they're from different base regions.
695 const MemRegion *LeftBase = LeftMR->getBaseRegion();
696 const MemRegion *RightBase = RightMR->getBaseRegion();
697 if (LeftBase != RightBase &&
698 !isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) {
703 return makeTruthVal(false, resultTy);
705 return makeTruthVal(true, resultTy);
709 // The two regions are from the same base region. See if they're both a
710 // type of region we know how to compare.
712 // FIXME: If/when there is a getAsRawOffset() for FieldRegions, this
713 // ElementRegion path and the FieldRegion path below should be unified.
714 if (const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR)) {
715 // First see if the right region is also an ElementRegion.
716 const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
720 // Next, see if the two ERs have the same super-region and matching types.
721 // FIXME: This should do something useful even if the types don't match,
722 // though if both indexes are constant the RegionRawOffset path will
723 // give the correct answer.
724 if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
725 LeftER->getElementType() == RightER->getElementType()) {
726 // Get the left index and cast it to the correct type.
727 // If the index is unknown or undefined, bail out here.
728 SVal LeftIndexVal = LeftER->getIndex();
729 NonLoc *LeftIndex = dyn_cast<NonLoc>(&LeftIndexVal);
732 LeftIndexVal = evalCastFromNonLoc(*LeftIndex, resultTy);
733 LeftIndex = dyn_cast<NonLoc>(&LeftIndexVal);
737 // Do the same for the right index.
738 SVal RightIndexVal = RightER->getIndex();
739 NonLoc *RightIndex = dyn_cast<NonLoc>(&RightIndexVal);
742 RightIndexVal = evalCastFromNonLoc(*RightIndex, resultTy);
743 RightIndex = dyn_cast<NonLoc>(&RightIndexVal);
747 // Actually perform the operation.
748 // evalBinOpNN expects the two indexes to already be the right type.
749 return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
752 // If the element indexes aren't comparable, see if the raw offsets are.
753 RegionRawOffset LeftOffset = LeftER->getAsArrayOffset();
754 RegionRawOffset RightOffset = RightER->getAsArrayOffset();
756 if (LeftOffset.getRegion() != NULL &&
757 LeftOffset.getRegion() == RightOffset.getRegion()) {
758 CharUnits left = LeftOffset.getOffset();
759 CharUnits right = RightOffset.getOffset();
765 return makeTruthVal(left < right, resultTy);
767 return makeTruthVal(left > right, resultTy);
769 return makeTruthVal(left <= right, resultTy);
771 return makeTruthVal(left >= right, resultTy);
773 return makeTruthVal(left == right, resultTy);
775 return makeTruthVal(left != right, resultTy);
779 // If we get here, we have no way of comparing the ElementRegions.
783 // See if both regions are fields of the same structure.
784 // FIXME: This doesn't handle nesting, inheritance, or Objective-C ivars.
785 if (const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR)) {
786 // Only comparisons are meaningful here!
787 if (!BinaryOperator::isComparisonOp(op))
790 // First see if the right region is also a FieldRegion.
791 const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
795 // Next, see if the two FRs have the same super-region.
796 // FIXME: This doesn't handle casts yet, and simply stripping the casts
798 if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
801 const FieldDecl *LeftFD = LeftFR->getDecl();
802 const FieldDecl *RightFD = RightFR->getDecl();
803 const RecordDecl *RD = LeftFD->getParent();
805 // Make sure the two FRs are from the same kind of record. Just in case!
806 // FIXME: This is probably where inheritance would be a problem.
807 if (RD != RightFD->getParent())
810 // We know for sure that the two fields are not the same, since that
811 // would have given us the same SVal.
813 return makeTruthVal(false, resultTy);
815 return makeTruthVal(true, resultTy);
817 // Iterate through the fields and see which one comes first.
818 // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
819 // members and the units in which bit-fields reside have addresses that
820 // increase in the order in which they are declared."
821 bool leftFirst = (op == BO_LT || op == BO_LE);
822 for (RecordDecl::field_iterator I = RD->field_begin(),
823 E = RD->field_end(); I!=E; ++I) {
825 return makeTruthVal(leftFirst, resultTy);
827 return makeTruthVal(!leftFirst, resultTy);
830 assert(false && "Fields not found in parent record's definition");
833 // If we get here, we have no way of comparing the regions.
839 SVal SimpleSValBuilder::evalBinOpLN(const GRState *state,
840 BinaryOperator::Opcode op,
841 Loc lhs, NonLoc rhs, QualType resultTy) {
843 // Special case: rhs is a zero constant.
844 if (rhs.isZeroConstant())
847 // Special case: 'rhs' is an integer that has the same width as a pointer and
848 // we are using the integer location in a comparison. Normally this cannot be
849 // triggered, but transfer functions like those for OSCommpareAndSwapBarrier32
850 // can generate comparisons that trigger this code.
851 // FIXME: Are all locations guaranteed to have pointer width?
852 if (BinaryOperator::isComparisonOp(op)) {
853 if (nonloc::ConcreteInt *rhsInt = dyn_cast<nonloc::ConcreteInt>(&rhs)) {
854 const llvm::APSInt *x = &rhsInt->getValue();
855 ASTContext &ctx = Context;
856 if (ctx.getTypeSize(ctx.VoidPtrTy) == x->getBitWidth()) {
857 // Convert the signedness of the integer (if necessary).
859 x = &getBasicValueFactory().getValue(*x, true);
861 return evalBinOpLL(state, op, lhs, loc::ConcreteInt(*x), resultTy);
866 // We are dealing with pointer arithmetic.
868 // Handle pointer arithmetic on constant values.
869 if (nonloc::ConcreteInt *rhsInt = dyn_cast<nonloc::ConcreteInt>(&rhs)) {
870 if (loc::ConcreteInt *lhsInt = dyn_cast<loc::ConcreteInt>(&lhs)) {
871 const llvm::APSInt &leftI = lhsInt->getValue();
872 assert(leftI.isUnsigned());
873 llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
875 // Convert the bitwidth of rightI. This should deal with overflow
876 // since we are dealing with concrete values.
877 rightI = rightI.extOrTrunc(leftI.getBitWidth());
879 // Offset the increment by the pointer size.
880 llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
881 rightI *= Multiplicand;
883 // Compute the adjusted pointer.
886 rightI = leftI + rightI;
889 rightI = leftI - rightI;
892 llvm_unreachable("Invalid pointer arithmetic operation");
894 return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
898 // Handle cases where 'lhs' is a region.
899 if (const MemRegion *region = lhs.getAsRegion()) {
900 rhs = cast<NonLoc>(convertToArrayIndex(rhs));
901 SVal index = UnknownVal();
902 const MemRegion *superR = 0;
903 QualType elementType;
905 if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
906 assert(op == BO_Add || op == BO_Sub);
907 index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
908 getArrayIndexType());
909 superR = elemReg->getSuperRegion();
910 elementType = elemReg->getElementType();
912 else if (isa<SubRegion>(region)) {
915 if (const PointerType *PT = resultTy->getAs<PointerType>()) {
916 elementType = PT->getPointeeType();
919 const ObjCObjectPointerType *OT =
920 resultTy->getAs<ObjCObjectPointerType>();
921 elementType = OT->getPointeeType();
925 if (NonLoc *indexV = dyn_cast<NonLoc>(&index)) {
926 return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
927 superR, getContext()));
933 const llvm::APSInt *SimpleSValBuilder::getKnownValue(const GRState *state,
935 if (V.isUnknownOrUndef())
938 if (loc::ConcreteInt* X = dyn_cast<loc::ConcreteInt>(&V))
939 return &X->getValue();
941 if (nonloc::ConcreteInt* X = dyn_cast<nonloc::ConcreteInt>(&V))
942 return &X->getValue();
944 if (SymbolRef Sym = V.getAsSymbol())
945 return state->getSymVal(Sym);
947 // FIXME: Add support for SymExprs.