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