1 // SimpleSValBuilder.cpp - A basic SValBuilder -----------------------*- C++ -*-
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines SimpleSValBuilder, a basic implementation of SValBuilder.
11 //
12 //===----------------------------------------------------------------------===//
13 
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 
18 using namespace clang;
19 using namespace ento;
20 
21 namespace {
22 class SimpleSValBuilder : public SValBuilder {
23 protected:
24   SVal dispatchCast(SVal val, QualType castTy) override;
25   SVal evalCastFromNonLoc(NonLoc val, QualType castTy) override;
26   SVal evalCastFromLoc(Loc val, QualType castTy) override;
27 
28 public:
29   SimpleSValBuilder(llvm::BumpPtrAllocator &alloc, ASTContext &context,
30                     ProgramStateManager &stateMgr)
31                     : SValBuilder(alloc, context, stateMgr) {}
32   ~SimpleSValBuilder() override {}
33 
34   SVal evalMinus(NonLoc val) override;
35   SVal evalComplement(NonLoc val) override;
36   SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op,
37                    NonLoc lhs, NonLoc rhs, QualType resultTy) override;
38   SVal evalBinOpLL(ProgramStateRef state, BinaryOperator::Opcode op,
39                    Loc lhs, Loc rhs, QualType resultTy) override;
40   SVal evalBinOpLN(ProgramStateRef state, BinaryOperator::Opcode op,
41                    Loc lhs, NonLoc rhs, QualType resultTy) override;
42 
43   /// getKnownValue - evaluates a given SVal. If the SVal has only one possible
44   ///  (integer) value, that value is returned. Otherwise, returns NULL.
45   const llvm::APSInt *getKnownValue(ProgramStateRef state, SVal V) override;
46 
47   SVal MakeSymIntVal(const SymExpr *LHS, BinaryOperator::Opcode op,
48                      const llvm::APSInt &RHS, QualType resultTy);
49 };
50 } // end anonymous namespace
51 
52 SValBuilder *ento::createSimpleSValBuilder(llvm::BumpPtrAllocator &alloc,
53                                            ASTContext &context,
54                                            ProgramStateManager &stateMgr) {
55   return new SimpleSValBuilder(alloc, context, stateMgr);
56 }
57 
58 //===----------------------------------------------------------------------===//
59 // Transfer function for Casts.
60 //===----------------------------------------------------------------------===//
61 
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);
66 }
67 
68 SVal SimpleSValBuilder::evalCastFromNonLoc(NonLoc val, QualType castTy) {
69 
70   bool isLocType = Loc::isLocType(castTy);
71 
72   if (val.getAs<nonloc::PointerToMember>())
73     return val;
74 
75   if (Optional<nonloc::LocAsInteger> LI = val.getAs<nonloc::LocAsInteger>()) {
76     if (isLocType)
77       return LI->getLoc();
78 
79     // FIXME: Correctly support promotions/truncations.
80     unsigned castSize = Context.getTypeSize(castTy);
81     if (castSize == LI->getNumBits())
82       return val;
83     return makeLocAsInteger(LI->getLoc(), castSize);
84   }
85 
86   if (const SymExpr *se = val.getAsSymbolicExpression()) {
87     QualType T = Context.getCanonicalType(se->getType());
88     // If types are the same or both are integers, ignore the cast.
89     // FIXME: Remove this hack when we support symbolic truncation/extension.
90     // HACK: If both castTy and T are integers, ignore the cast.  This is
91     // not a permanent solution.  Eventually we want to precisely handle
92     // extension/truncation of symbolic integers.  This prevents us from losing
93     // precision when we assign 'x = y' and 'y' is symbolic and x and y are
94     // different integer types.
95    if (haveSameType(T, castTy))
96       return val;
97 
98     if (!isLocType)
99       return makeNonLoc(se, T, castTy);
100     return UnknownVal();
101   }
102 
103   // If value is a non-integer constant, produce unknown.
104   if (!val.getAs<nonloc::ConcreteInt>())
105     return UnknownVal();
106 
107   // Handle casts to a boolean type.
108   if (castTy->isBooleanType()) {
109     bool b = val.castAs<nonloc::ConcreteInt>().getValue().getBoolValue();
110     return makeTruthVal(b, castTy);
111   }
112 
113   // Only handle casts from integers to integers - if val is an integer constant
114   // being cast to a non-integer type, produce unknown.
115   if (!isLocType && !castTy->isIntegralOrEnumerationType())
116     return UnknownVal();
117 
118   llvm::APSInt i = val.castAs<nonloc::ConcreteInt>().getValue();
119   BasicVals.getAPSIntType(castTy).apply(i);
120 
121   if (isLocType)
122     return makeIntLocVal(i);
123   else
124     return makeIntVal(i);
125 }
126 
127 SVal SimpleSValBuilder::evalCastFromLoc(Loc val, QualType castTy) {
128 
129   // Casts from pointers -> pointers, just return the lval.
130   //
131   // Casts from pointers -> references, just return the lval.  These
132   //   can be introduced by the frontend for corner cases, e.g
133   //   casting from va_list* to __builtin_va_list&.
134   //
135   if (Loc::isLocType(castTy) || castTy->isReferenceType())
136     return val;
137 
138   // FIXME: Handle transparent unions where a value can be "transparently"
139   //  lifted into a union type.
140   if (castTy->isUnionType())
141     return UnknownVal();
142 
143   // Casting a Loc to a bool will almost always be true,
144   // unless this is a weak function or a symbolic region.
145   if (castTy->isBooleanType()) {
146     switch (val.getSubKind()) {
147       case loc::MemRegionValKind: {
148         const MemRegion *R = val.castAs<loc::MemRegionVal>().getRegion();
149         if (const FunctionCodeRegion *FTR = dyn_cast<FunctionCodeRegion>(R))
150           if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FTR->getDecl()))
151             if (FD->isWeak())
152               // FIXME: Currently we are using an extent symbol here,
153               // because there are no generic region address metadata
154               // symbols to use, only content metadata.
155               return nonloc::SymbolVal(SymMgr.getExtentSymbol(FTR));
156 
157         if (const SymbolicRegion *SymR = R->getSymbolicBase())
158           return nonloc::SymbolVal(SymR->getSymbol());
159 
160         // FALL-THROUGH
161       }
162 
163       case loc::GotoLabelKind:
164         // Labels and non-symbolic memory regions are always true.
165         return makeTruthVal(true, castTy);
166     }
167   }
168 
169   if (castTy->isIntegralOrEnumerationType()) {
170     unsigned BitWidth = Context.getTypeSize(castTy);
171 
172     if (!val.getAs<loc::ConcreteInt>())
173       return makeLocAsInteger(val, BitWidth);
174 
175     llvm::APSInt i = val.castAs<loc::ConcreteInt>().getValue();
176     BasicVals.getAPSIntType(castTy).apply(i);
177     return makeIntVal(i);
178   }
179 
180   // All other cases: return 'UnknownVal'.  This includes casting pointers
181   // to floats, which is probably badness it itself, but this is a good
182   // intermediate solution until we do something better.
183   return UnknownVal();
184 }
185 
186 //===----------------------------------------------------------------------===//
187 // Transfer function for unary operators.
188 //===----------------------------------------------------------------------===//
189 
190 SVal SimpleSValBuilder::evalMinus(NonLoc val) {
191   switch (val.getSubKind()) {
192   case nonloc::ConcreteIntKind:
193     return val.castAs<nonloc::ConcreteInt>().evalMinus(*this);
194   default:
195     return UnknownVal();
196   }
197 }
198 
199 SVal SimpleSValBuilder::evalComplement(NonLoc X) {
200   switch (X.getSubKind()) {
201   case nonloc::ConcreteIntKind:
202     return X.castAs<nonloc::ConcreteInt>().evalComplement(*this);
203   default:
204     return UnknownVal();
205   }
206 }
207 
208 //===----------------------------------------------------------------------===//
209 // Transfer function for binary operators.
210 //===----------------------------------------------------------------------===//
211 
212 SVal SimpleSValBuilder::MakeSymIntVal(const SymExpr *LHS,
213                                     BinaryOperator::Opcode op,
214                                     const llvm::APSInt &RHS,
215                                     QualType resultTy) {
216   bool isIdempotent = false;
217 
218   // Check for a few special cases with known reductions first.
219   switch (op) {
220   default:
221     // We can't reduce this case; just treat it normally.
222     break;
223   case BO_Mul:
224     // a*0 and a*1
225     if (RHS == 0)
226       return makeIntVal(0, resultTy);
227     else if (RHS == 1)
228       isIdempotent = true;
229     break;
230   case BO_Div:
231     // a/0 and a/1
232     if (RHS == 0)
233       // This is also handled elsewhere.
234       return UndefinedVal();
235     else if (RHS == 1)
236       isIdempotent = true;
237     break;
238   case BO_Rem:
239     // a%0 and a%1
240     if (RHS == 0)
241       // This is also handled elsewhere.
242       return UndefinedVal();
243     else if (RHS == 1)
244       return makeIntVal(0, resultTy);
245     break;
246   case BO_Add:
247   case BO_Sub:
248   case BO_Shl:
249   case BO_Shr:
250   case BO_Xor:
251     // a+0, a-0, a<<0, a>>0, a^0
252     if (RHS == 0)
253       isIdempotent = true;
254     break;
255   case BO_And:
256     // a&0 and a&(~0)
257     if (RHS == 0)
258       return makeIntVal(0, resultTy);
259     else if (RHS.isAllOnesValue())
260       isIdempotent = true;
261     break;
262   case BO_Or:
263     // a|0 and a|(~0)
264     if (RHS == 0)
265       isIdempotent = true;
266     else if (RHS.isAllOnesValue()) {
267       const llvm::APSInt &Result = BasicVals.Convert(resultTy, RHS);
268       return nonloc::ConcreteInt(Result);
269     }
270     break;
271   }
272 
273   // Idempotent ops (like a*1) can still change the type of an expression.
274   // Wrap the LHS up in a NonLoc again and let evalCastFromNonLoc do the
275   // dirty work.
276   if (isIdempotent)
277       return evalCastFromNonLoc(nonloc::SymbolVal(LHS), resultTy);
278 
279   // If we reach this point, the expression cannot be simplified.
280   // Make a SymbolVal for the entire expression, after converting the RHS.
281   const llvm::APSInt *ConvertedRHS = &RHS;
282   if (BinaryOperator::isComparisonOp(op)) {
283     // We're looking for a type big enough to compare the symbolic value
284     // with the given constant.
285     // FIXME: This is an approximation of Sema::UsualArithmeticConversions.
286     ASTContext &Ctx = getContext();
287     QualType SymbolType = LHS->getType();
288     uint64_t ValWidth = RHS.getBitWidth();
289     uint64_t TypeWidth = Ctx.getTypeSize(SymbolType);
290 
291     if (ValWidth < TypeWidth) {
292       // If the value is too small, extend it.
293       ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
294     } else if (ValWidth == TypeWidth) {
295       // If the value is signed but the symbol is unsigned, do the comparison
296       // in unsigned space. [C99 6.3.1.8]
297       // (For the opposite case, the value is already unsigned.)
298       if (RHS.isSigned() && !SymbolType->isSignedIntegerOrEnumerationType())
299         ConvertedRHS = &BasicVals.Convert(SymbolType, RHS);
300     }
301   } else
302     ConvertedRHS = &BasicVals.Convert(resultTy, RHS);
303 
304   return makeNonLoc(LHS, op, *ConvertedRHS, resultTy);
305 }
306 
307 SVal SimpleSValBuilder::evalBinOpNN(ProgramStateRef state,
308                                   BinaryOperator::Opcode op,
309                                   NonLoc lhs, NonLoc rhs,
310                                   QualType resultTy)  {
311   NonLoc InputLHS = lhs;
312   NonLoc InputRHS = rhs;
313 
314   // Handle trivial case where left-side and right-side are the same.
315   if (lhs == rhs)
316     switch (op) {
317       default:
318         break;
319       case BO_EQ:
320       case BO_LE:
321       case BO_GE:
322         return makeTruthVal(true, resultTy);
323       case BO_LT:
324       case BO_GT:
325       case BO_NE:
326         return makeTruthVal(false, resultTy);
327       case BO_Xor:
328       case BO_Sub:
329         if (resultTy->isIntegralOrEnumerationType())
330           return makeIntVal(0, resultTy);
331         return evalCastFromNonLoc(makeIntVal(0, /*Unsigned=*/false), resultTy);
332       case BO_Or:
333       case BO_And:
334         return evalCastFromNonLoc(lhs, resultTy);
335     }
336 
337   while (1) {
338     switch (lhs.getSubKind()) {
339     default:
340       return makeSymExprValNN(state, op, lhs, rhs, resultTy);
341     case nonloc::PointerToMemberKind: {
342       assert(rhs.getSubKind() == nonloc::PointerToMemberKind &&
343              "Both SVals should have pointer-to-member-type");
344       auto LPTM = lhs.castAs<nonloc::PointerToMember>(),
345            RPTM = rhs.castAs<nonloc::PointerToMember>();
346       auto LPTMD = LPTM.getPTMData(), RPTMD = RPTM.getPTMData();
347       switch (op) {
348         case BO_EQ:
349           return makeTruthVal(LPTMD == RPTMD, resultTy);
350         case BO_NE:
351           return makeTruthVal(LPTMD != RPTMD, resultTy);
352         default:
353           return UnknownVal();
354       }
355     }
356     case nonloc::LocAsIntegerKind: {
357       Loc lhsL = lhs.castAs<nonloc::LocAsInteger>().getLoc();
358       switch (rhs.getSubKind()) {
359         case nonloc::LocAsIntegerKind:
360           return evalBinOpLL(state, op, lhsL,
361                              rhs.castAs<nonloc::LocAsInteger>().getLoc(),
362                              resultTy);
363         case nonloc::ConcreteIntKind: {
364           // Transform the integer into a location and compare.
365           // FIXME: This only makes sense for comparisons. If we want to, say,
366           // add 1 to a LocAsInteger, we'd better unpack the Loc and add to it,
367           // then pack it back into a LocAsInteger.
368           llvm::APSInt i = rhs.castAs<nonloc::ConcreteInt>().getValue();
369           BasicVals.getAPSIntType(Context.VoidPtrTy).apply(i);
370           return evalBinOpLL(state, op, lhsL, makeLoc(i), resultTy);
371         }
372         default:
373           switch (op) {
374             case BO_EQ:
375               return makeTruthVal(false, resultTy);
376             case BO_NE:
377               return makeTruthVal(true, resultTy);
378             default:
379               // This case also handles pointer arithmetic.
380               return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
381           }
382       }
383     }
384     case nonloc::ConcreteIntKind: {
385       llvm::APSInt LHSValue = lhs.castAs<nonloc::ConcreteInt>().getValue();
386 
387       // If we're dealing with two known constants, just perform the operation.
388       if (const llvm::APSInt *KnownRHSValue = getKnownValue(state, rhs)) {
389         llvm::APSInt RHSValue = *KnownRHSValue;
390         if (BinaryOperator::isComparisonOp(op)) {
391           // We're looking for a type big enough to compare the two values.
392           // FIXME: This is not correct. char + short will result in a promotion
393           // to int. Unfortunately we have lost types by this point.
394           APSIntType CompareType = std::max(APSIntType(LHSValue),
395                                             APSIntType(RHSValue));
396           CompareType.apply(LHSValue);
397           CompareType.apply(RHSValue);
398         } else if (!BinaryOperator::isShiftOp(op)) {
399           APSIntType IntType = BasicVals.getAPSIntType(resultTy);
400           IntType.apply(LHSValue);
401           IntType.apply(RHSValue);
402         }
403 
404         const llvm::APSInt *Result =
405           BasicVals.evalAPSInt(op, LHSValue, RHSValue);
406         if (!Result)
407           return UndefinedVal();
408 
409         return nonloc::ConcreteInt(*Result);
410       }
411 
412       // Swap the left and right sides and flip the operator if doing so
413       // allows us to better reason about the expression (this is a form
414       // of expression canonicalization).
415       // While we're at it, catch some special cases for non-commutative ops.
416       switch (op) {
417       case BO_LT:
418       case BO_GT:
419       case BO_LE:
420       case BO_GE:
421         op = BinaryOperator::reverseComparisonOp(op);
422         // FALL-THROUGH
423       case BO_EQ:
424       case BO_NE:
425       case BO_Add:
426       case BO_Mul:
427       case BO_And:
428       case BO_Xor:
429       case BO_Or:
430         std::swap(lhs, rhs);
431         continue;
432       case BO_Shr:
433         // (~0)>>a
434         if (LHSValue.isAllOnesValue() && LHSValue.isSigned())
435           return evalCastFromNonLoc(lhs, resultTy);
436         // FALL-THROUGH
437       case BO_Shl:
438         // 0<<a and 0>>a
439         if (LHSValue == 0)
440           return evalCastFromNonLoc(lhs, resultTy);
441         return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
442       default:
443         return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
444       }
445     }
446     case nonloc::SymbolValKind: {
447       // We only handle LHS as simple symbols or SymIntExprs.
448       SymbolRef Sym = lhs.castAs<nonloc::SymbolVal>().getSymbol();
449 
450       // LHS is a symbolic expression.
451       if (const SymIntExpr *symIntExpr = dyn_cast<SymIntExpr>(Sym)) {
452 
453         // Is this a logical not? (!x is represented as x == 0.)
454         if (op == BO_EQ && rhs.isZeroConstant()) {
455           // We know how to negate certain expressions. Simplify them here.
456 
457           BinaryOperator::Opcode opc = symIntExpr->getOpcode();
458           switch (opc) {
459           default:
460             // We don't know how to negate this operation.
461             // Just handle it as if it were a normal comparison to 0.
462             break;
463           case BO_LAnd:
464           case BO_LOr:
465             llvm_unreachable("Logical operators handled by branching logic.");
466           case BO_Assign:
467           case BO_MulAssign:
468           case BO_DivAssign:
469           case BO_RemAssign:
470           case BO_AddAssign:
471           case BO_SubAssign:
472           case BO_ShlAssign:
473           case BO_ShrAssign:
474           case BO_AndAssign:
475           case BO_XorAssign:
476           case BO_OrAssign:
477           case BO_Comma:
478             llvm_unreachable("'=' and ',' operators handled by ExprEngine.");
479           case BO_PtrMemD:
480           case BO_PtrMemI:
481             llvm_unreachable("Pointer arithmetic not handled here.");
482           case BO_LT:
483           case BO_GT:
484           case BO_LE:
485           case BO_GE:
486           case BO_EQ:
487           case BO_NE:
488             assert(resultTy->isBooleanType() ||
489                    resultTy == getConditionType());
490             assert(symIntExpr->getType()->isBooleanType() ||
491                    getContext().hasSameUnqualifiedType(symIntExpr->getType(),
492                                                        getConditionType()));
493             // Negate the comparison and make a value.
494             opc = BinaryOperator::negateComparisonOp(opc);
495             return makeNonLoc(symIntExpr->getLHS(), opc,
496                 symIntExpr->getRHS(), resultTy);
497           }
498         }
499 
500         // For now, only handle expressions whose RHS is a constant.
501         if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs)) {
502           // If both the LHS and the current expression are additive,
503           // fold their constants and try again.
504           if (BinaryOperator::isAdditiveOp(op)) {
505             BinaryOperator::Opcode lop = symIntExpr->getOpcode();
506             if (BinaryOperator::isAdditiveOp(lop)) {
507               // Convert the two constants to a common type, then combine them.
508 
509               // resultTy may not be the best type to convert to, but it's
510               // probably the best choice in expressions with mixed type
511               // (such as x+1U+2LL). The rules for implicit conversions should
512               // choose a reasonable type to preserve the expression, and will
513               // at least match how the value is going to be used.
514               APSIntType IntType = BasicVals.getAPSIntType(resultTy);
515               const llvm::APSInt &first = IntType.convert(symIntExpr->getRHS());
516               const llvm::APSInt &second = IntType.convert(*RHSValue);
517 
518               const llvm::APSInt *newRHS;
519               if (lop == op)
520                 newRHS = BasicVals.evalAPSInt(BO_Add, first, second);
521               else
522                 newRHS = BasicVals.evalAPSInt(BO_Sub, first, second);
523 
524               assert(newRHS && "Invalid operation despite common type!");
525               rhs = nonloc::ConcreteInt(*newRHS);
526               lhs = nonloc::SymbolVal(symIntExpr->getLHS());
527               op = lop;
528               continue;
529             }
530           }
531 
532           // Otherwise, make a SymIntExpr out of the expression.
533           return MakeSymIntVal(symIntExpr, op, *RHSValue, resultTy);
534         }
535       }
536 
537       // Does the symbolic expression simplify to a constant?
538       // If so, "fold" the constant by setting 'lhs' to a ConcreteInt
539       // and try again.
540       ConstraintManager &CMgr = state->getConstraintManager();
541       if (const llvm::APSInt *Constant = CMgr.getSymVal(state, Sym)) {
542         lhs = nonloc::ConcreteInt(*Constant);
543         continue;
544       }
545 
546       // Is the RHS a constant?
547       if (const llvm::APSInt *RHSValue = getKnownValue(state, rhs))
548         return MakeSymIntVal(Sym, op, *RHSValue, resultTy);
549 
550       // Give up -- this is not a symbolic expression we can handle.
551       return makeSymExprValNN(state, op, InputLHS, InputRHS, resultTy);
552     }
553     }
554   }
555 }
556 
557 static SVal evalBinOpFieldRegionFieldRegion(const FieldRegion *LeftFR,
558                                             const FieldRegion *RightFR,
559                                             BinaryOperator::Opcode op,
560                                             QualType resultTy,
561                                             SimpleSValBuilder &SVB) {
562   // Only comparisons are meaningful here!
563   if (!BinaryOperator::isComparisonOp(op))
564     return UnknownVal();
565 
566   // Next, see if the two FRs have the same super-region.
567   // FIXME: This doesn't handle casts yet, and simply stripping the casts
568   // doesn't help.
569   if (LeftFR->getSuperRegion() != RightFR->getSuperRegion())
570     return UnknownVal();
571 
572   const FieldDecl *LeftFD = LeftFR->getDecl();
573   const FieldDecl *RightFD = RightFR->getDecl();
574   const RecordDecl *RD = LeftFD->getParent();
575 
576   // Make sure the two FRs are from the same kind of record. Just in case!
577   // FIXME: This is probably where inheritance would be a problem.
578   if (RD != RightFD->getParent())
579     return UnknownVal();
580 
581   // We know for sure that the two fields are not the same, since that
582   // would have given us the same SVal.
583   if (op == BO_EQ)
584     return SVB.makeTruthVal(false, resultTy);
585   if (op == BO_NE)
586     return SVB.makeTruthVal(true, resultTy);
587 
588   // Iterate through the fields and see which one comes first.
589   // [C99 6.7.2.1.13] "Within a structure object, the non-bit-field
590   // members and the units in which bit-fields reside have addresses that
591   // increase in the order in which they are declared."
592   bool leftFirst = (op == BO_LT || op == BO_LE);
593   for (const auto *I : RD->fields()) {
594     if (I == LeftFD)
595       return SVB.makeTruthVal(leftFirst, resultTy);
596     if (I == RightFD)
597       return SVB.makeTruthVal(!leftFirst, resultTy);
598   }
599 
600   llvm_unreachable("Fields not found in parent record's definition");
601 }
602 
603 // FIXME: all this logic will change if/when we have MemRegion::getLocation().
604 SVal SimpleSValBuilder::evalBinOpLL(ProgramStateRef state,
605                                   BinaryOperator::Opcode op,
606                                   Loc lhs, Loc rhs,
607                                   QualType resultTy) {
608   // Only comparisons and subtractions are valid operations on two pointers.
609   // See [C99 6.5.5 through 6.5.14] or [C++0x 5.6 through 5.15].
610   // However, if a pointer is casted to an integer, evalBinOpNN may end up
611   // calling this function with another operation (PR7527). We don't attempt to
612   // model this for now, but it could be useful, particularly when the
613   // "location" is actually an integer value that's been passed through a void*.
614   if (!(BinaryOperator::isComparisonOp(op) || op == BO_Sub))
615     return UnknownVal();
616 
617   // Special cases for when both sides are identical.
618   if (lhs == rhs) {
619     switch (op) {
620     default:
621       llvm_unreachable("Unimplemented operation for two identical values");
622     case BO_Sub:
623       return makeZeroVal(resultTy);
624     case BO_EQ:
625     case BO_LE:
626     case BO_GE:
627       return makeTruthVal(true, resultTy);
628     case BO_NE:
629     case BO_LT:
630     case BO_GT:
631       return makeTruthVal(false, resultTy);
632     }
633   }
634 
635   switch (lhs.getSubKind()) {
636   default:
637     llvm_unreachable("Ordering not implemented for this Loc.");
638 
639   case loc::GotoLabelKind:
640     // The only thing we know about labels is that they're non-null.
641     if (rhs.isZeroConstant()) {
642       switch (op) {
643       default:
644         break;
645       case BO_Sub:
646         return evalCastFromLoc(lhs, resultTy);
647       case BO_EQ:
648       case BO_LE:
649       case BO_LT:
650         return makeTruthVal(false, resultTy);
651       case BO_NE:
652       case BO_GT:
653       case BO_GE:
654         return makeTruthVal(true, resultTy);
655       }
656     }
657     // There may be two labels for the same location, and a function region may
658     // have the same address as a label at the start of the function (depending
659     // on the ABI).
660     // FIXME: we can probably do a comparison against other MemRegions, though.
661     // FIXME: is there a way to tell if two labels refer to the same location?
662     return UnknownVal();
663 
664   case loc::ConcreteIntKind: {
665     // If one of the operands is a symbol and the other is a constant,
666     // build an expression for use by the constraint manager.
667     if (SymbolRef rSym = rhs.getAsLocSymbol()) {
668       // We can only build expressions with symbols on the left,
669       // so we need a reversible operator.
670       if (!BinaryOperator::isComparisonOp(op))
671         return UnknownVal();
672 
673       const llvm::APSInt &lVal = lhs.castAs<loc::ConcreteInt>().getValue();
674       op = BinaryOperator::reverseComparisonOp(op);
675       return makeNonLoc(rSym, op, lVal, resultTy);
676     }
677 
678     // If both operands are constants, just perform the operation.
679     if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
680       SVal ResultVal =
681           lhs.castAs<loc::ConcreteInt>().evalBinOp(BasicVals, op, *rInt);
682       if (Optional<NonLoc> Result = ResultVal.getAs<NonLoc>())
683         return evalCastFromNonLoc(*Result, resultTy);
684 
685       assert(!ResultVal.getAs<Loc>() && "Loc-Loc ops should not produce Locs");
686       return UnknownVal();
687     }
688 
689     // Special case comparisons against NULL.
690     // This must come after the test if the RHS is a symbol, which is used to
691     // build constraints. The address of any non-symbolic region is guaranteed
692     // to be non-NULL, as is any label.
693     assert(rhs.getAs<loc::MemRegionVal>() || rhs.getAs<loc::GotoLabel>());
694     if (lhs.isZeroConstant()) {
695       switch (op) {
696       default:
697         break;
698       case BO_EQ:
699       case BO_GT:
700       case BO_GE:
701         return makeTruthVal(false, resultTy);
702       case BO_NE:
703       case BO_LT:
704       case BO_LE:
705         return makeTruthVal(true, resultTy);
706       }
707     }
708 
709     // Comparing an arbitrary integer to a region or label address is
710     // completely unknowable.
711     return UnknownVal();
712   }
713   case loc::MemRegionValKind: {
714     if (Optional<loc::ConcreteInt> rInt = rhs.getAs<loc::ConcreteInt>()) {
715       // If one of the operands is a symbol and the other is a constant,
716       // build an expression for use by the constraint manager.
717       if (SymbolRef lSym = lhs.getAsLocSymbol(true))
718         return MakeSymIntVal(lSym, op, rInt->getValue(), resultTy);
719 
720       // Special case comparisons to NULL.
721       // This must come after the test if the LHS is a symbol, which is used to
722       // build constraints. The address of any non-symbolic region is guaranteed
723       // to be non-NULL.
724       if (rInt->isZeroConstant()) {
725         if (op == BO_Sub)
726           return evalCastFromLoc(lhs, resultTy);
727 
728         if (BinaryOperator::isComparisonOp(op)) {
729           QualType boolType = getContext().BoolTy;
730           NonLoc l = evalCastFromLoc(lhs, boolType).castAs<NonLoc>();
731           NonLoc r = makeTruthVal(false, boolType).castAs<NonLoc>();
732           return evalBinOpNN(state, op, l, r, resultTy);
733         }
734       }
735 
736       // Comparing a region to an arbitrary integer is completely unknowable.
737       return UnknownVal();
738     }
739 
740     // Get both values as regions, if possible.
741     const MemRegion *LeftMR = lhs.getAsRegion();
742     assert(LeftMR && "MemRegionValKind SVal doesn't have a region!");
743 
744     const MemRegion *RightMR = rhs.getAsRegion();
745     if (!RightMR)
746       // The RHS is probably a label, which in theory could address a region.
747       // FIXME: we can probably make a more useful statement about non-code
748       // regions, though.
749       return UnknownVal();
750 
751     const MemRegion *LeftBase = LeftMR->getBaseRegion();
752     const MemRegion *RightBase = RightMR->getBaseRegion();
753     const MemSpaceRegion *LeftMS = LeftBase->getMemorySpace();
754     const MemSpaceRegion *RightMS = RightBase->getMemorySpace();
755     const MemSpaceRegion *UnknownMS = MemMgr.getUnknownRegion();
756 
757     // If the two regions are from different known memory spaces they cannot be
758     // equal. Also, assume that no symbolic region (whose memory space is
759     // unknown) is on the stack.
760     if (LeftMS != RightMS &&
761         ((LeftMS != UnknownMS && RightMS != UnknownMS) ||
762          (isa<StackSpaceRegion>(LeftMS) || isa<StackSpaceRegion>(RightMS)))) {
763       switch (op) {
764       default:
765         return UnknownVal();
766       case BO_EQ:
767         return makeTruthVal(false, resultTy);
768       case BO_NE:
769         return makeTruthVal(true, resultTy);
770       }
771     }
772 
773     // If both values wrap regions, see if they're from different base regions.
774     // Note, heap base symbolic regions are assumed to not alias with
775     // each other; for example, we assume that malloc returns different address
776     // on each invocation.
777     // FIXME: ObjC object pointers always reside on the heap, but currently
778     // we treat their memory space as unknown, because symbolic pointers
779     // to ObjC objects may alias. There should be a way to construct
780     // possibly-aliasing heap-based regions. For instance, MacOSXApiChecker
781     // guesses memory space for ObjC object pointers manually instead of
782     // relying on us.
783     if (LeftBase != RightBase &&
784         ((!isa<SymbolicRegion>(LeftBase) && !isa<SymbolicRegion>(RightBase)) ||
785          (isa<HeapSpaceRegion>(LeftMS) || isa<HeapSpaceRegion>(RightMS))) ){
786       switch (op) {
787       default:
788         return UnknownVal();
789       case BO_EQ:
790         return makeTruthVal(false, resultTy);
791       case BO_NE:
792         return makeTruthVal(true, resultTy);
793       }
794     }
795 
796     // Handle special cases for when both regions are element regions.
797     const ElementRegion *RightER = dyn_cast<ElementRegion>(RightMR);
798     const ElementRegion *LeftER = dyn_cast<ElementRegion>(LeftMR);
799     if (RightER && LeftER) {
800       // Next, see if the two ERs have the same super-region and matching types.
801       // FIXME: This should do something useful even if the types don't match,
802       // though if both indexes are constant the RegionRawOffset path will
803       // give the correct answer.
804       if (LeftER->getSuperRegion() == RightER->getSuperRegion() &&
805           LeftER->getElementType() == RightER->getElementType()) {
806         // Get the left index and cast it to the correct type.
807         // If the index is unknown or undefined, bail out here.
808         SVal LeftIndexVal = LeftER->getIndex();
809         Optional<NonLoc> LeftIndex = LeftIndexVal.getAs<NonLoc>();
810         if (!LeftIndex)
811           return UnknownVal();
812         LeftIndexVal = evalCastFromNonLoc(*LeftIndex, ArrayIndexTy);
813         LeftIndex = LeftIndexVal.getAs<NonLoc>();
814         if (!LeftIndex)
815           return UnknownVal();
816 
817         // Do the same for the right index.
818         SVal RightIndexVal = RightER->getIndex();
819         Optional<NonLoc> RightIndex = RightIndexVal.getAs<NonLoc>();
820         if (!RightIndex)
821           return UnknownVal();
822         RightIndexVal = evalCastFromNonLoc(*RightIndex, ArrayIndexTy);
823         RightIndex = RightIndexVal.getAs<NonLoc>();
824         if (!RightIndex)
825           return UnknownVal();
826 
827         // Actually perform the operation.
828         // evalBinOpNN expects the two indexes to already be the right type.
829         return evalBinOpNN(state, op, *LeftIndex, *RightIndex, resultTy);
830       }
831     }
832 
833     // Special handling of the FieldRegions, even with symbolic offsets.
834     const FieldRegion *RightFR = dyn_cast<FieldRegion>(RightMR);
835     const FieldRegion *LeftFR = dyn_cast<FieldRegion>(LeftMR);
836     if (RightFR && LeftFR) {
837       SVal R = evalBinOpFieldRegionFieldRegion(LeftFR, RightFR, op, resultTy,
838                                                *this);
839       if (!R.isUnknown())
840         return R;
841     }
842 
843     // Compare the regions using the raw offsets.
844     RegionOffset LeftOffset = LeftMR->getAsOffset();
845     RegionOffset RightOffset = RightMR->getAsOffset();
846 
847     if (LeftOffset.getRegion() != nullptr &&
848         LeftOffset.getRegion() == RightOffset.getRegion() &&
849         !LeftOffset.hasSymbolicOffset() && !RightOffset.hasSymbolicOffset()) {
850       int64_t left = LeftOffset.getOffset();
851       int64_t right = RightOffset.getOffset();
852 
853       switch (op) {
854         default:
855           return UnknownVal();
856         case BO_LT:
857           return makeTruthVal(left < right, resultTy);
858         case BO_GT:
859           return makeTruthVal(left > right, resultTy);
860         case BO_LE:
861           return makeTruthVal(left <= right, resultTy);
862         case BO_GE:
863           return makeTruthVal(left >= right, resultTy);
864         case BO_EQ:
865           return makeTruthVal(left == right, resultTy);
866         case BO_NE:
867           return makeTruthVal(left != right, resultTy);
868       }
869     }
870 
871     // At this point we're not going to get a good answer, but we can try
872     // conjuring an expression instead.
873     SymbolRef LHSSym = lhs.getAsLocSymbol();
874     SymbolRef RHSSym = rhs.getAsLocSymbol();
875     if (LHSSym && RHSSym)
876       return makeNonLoc(LHSSym, op, RHSSym, resultTy);
877 
878     // If we get here, we have no way of comparing the regions.
879     return UnknownVal();
880   }
881   }
882 }
883 
884 SVal SimpleSValBuilder::evalBinOpLN(ProgramStateRef state,
885                                   BinaryOperator::Opcode op,
886                                   Loc lhs, NonLoc rhs, QualType resultTy) {
887   if (op >= BO_PtrMemD && op <= BO_PtrMemI) {
888     if (auto PTMSV = rhs.getAs<nonloc::PointerToMember>()) {
889       if (PTMSV->isNullMemberPointer())
890         return UndefinedVal();
891       if (const FieldDecl *FD = PTMSV->getDeclAs<FieldDecl>()) {
892         SVal Result = lhs;
893 
894         for (const auto &I : *PTMSV)
895           Result = StateMgr.getStoreManager().evalDerivedToBase(
896               Result, I->getType(),I->isVirtual());
897         return state->getLValue(FD, Result);
898       }
899     }
900 
901     return rhs;
902   }
903 
904   assert(!BinaryOperator::isComparisonOp(op) &&
905          "arguments to comparison ops must be of the same type");
906 
907   // Special case: rhs is a zero constant.
908   if (rhs.isZeroConstant())
909     return lhs;
910 
911   // We are dealing with pointer arithmetic.
912 
913   // Handle pointer arithmetic on constant values.
914   if (Optional<nonloc::ConcreteInt> rhsInt = rhs.getAs<nonloc::ConcreteInt>()) {
915     if (Optional<loc::ConcreteInt> lhsInt = lhs.getAs<loc::ConcreteInt>()) {
916       const llvm::APSInt &leftI = lhsInt->getValue();
917       assert(leftI.isUnsigned());
918       llvm::APSInt rightI(rhsInt->getValue(), /* isUnsigned */ true);
919 
920       // Convert the bitwidth of rightI.  This should deal with overflow
921       // since we are dealing with concrete values.
922       rightI = rightI.extOrTrunc(leftI.getBitWidth());
923 
924       // Offset the increment by the pointer size.
925       llvm::APSInt Multiplicand(rightI.getBitWidth(), /* isUnsigned */ true);
926       rightI *= Multiplicand;
927 
928       // Compute the adjusted pointer.
929       switch (op) {
930         case BO_Add:
931           rightI = leftI + rightI;
932           break;
933         case BO_Sub:
934           rightI = leftI - rightI;
935           break;
936         default:
937           llvm_unreachable("Invalid pointer arithmetic operation");
938       }
939       return loc::ConcreteInt(getBasicValueFactory().getValue(rightI));
940     }
941   }
942 
943   // Handle cases where 'lhs' is a region.
944   if (const MemRegion *region = lhs.getAsRegion()) {
945     rhs = convertToArrayIndex(rhs).castAs<NonLoc>();
946     SVal index = UnknownVal();
947     const MemRegion *superR = nullptr;
948     // We need to know the type of the pointer in order to add an integer to it.
949     // Depending on the type, different amount of bytes is added.
950     QualType elementType;
951 
952     if (const ElementRegion *elemReg = dyn_cast<ElementRegion>(region)) {
953       assert(op == BO_Add || op == BO_Sub);
954       index = evalBinOpNN(state, op, elemReg->getIndex(), rhs,
955                           getArrayIndexType());
956       superR = elemReg->getSuperRegion();
957       elementType = elemReg->getElementType();
958     }
959     else if (isa<SubRegion>(region)) {
960       assert(op == BO_Add || op == BO_Sub);
961       index = (op == BO_Add) ? rhs : evalMinus(rhs);
962       superR = region;
963       // TODO: Is this actually reliable? Maybe improving our MemRegion
964       // hierarchy to provide typed regions for all non-void pointers would be
965       // better. For instance, we cannot extend this towards LocAsInteger
966       // operations, where result type of the expression is integer.
967       if (resultTy->isAnyPointerType())
968         elementType = resultTy->getPointeeType();
969     }
970 
971     if (Optional<NonLoc> indexV = index.getAs<NonLoc>()) {
972       return loc::MemRegionVal(MemMgr.getElementRegion(elementType, *indexV,
973                                                        superR, getContext()));
974     }
975   }
976   return UnknownVal();
977 }
978 
979 const llvm::APSInt *SimpleSValBuilder::getKnownValue(ProgramStateRef state,
980                                                    SVal V) {
981   if (V.isUnknownOrUndef())
982     return nullptr;
983 
984   if (Optional<loc::ConcreteInt> X = V.getAs<loc::ConcreteInt>())
985     return &X->getValue();
986 
987   if (Optional<nonloc::ConcreteInt> X = V.getAs<nonloc::ConcreteInt>())
988     return &X->getValue();
989 
990   if (SymbolRef Sym = V.getAsSymbol())
991     return state->getConstraintManager().getSymVal(state, Sym);
992 
993   // FIXME: Add support for SymExprs.
994   return nullptr;
995 }
996