1226586Sdim//=-- ExprEngineC.cpp - ExprEngine support for C expressions ----*- C++ -*-===//
2226586Sdim//
3226586Sdim//                     The LLVM Compiler Infrastructure
4226586Sdim//
5226586Sdim// This file is distributed under the University of Illinois Open Source
6226586Sdim// License. See LICENSE.TXT for details.
7226586Sdim//
8226586Sdim//===----------------------------------------------------------------------===//
9226586Sdim//
10226586Sdim//  This file defines ExprEngine's support for C expressions.
11226586Sdim//
12226586Sdim//===----------------------------------------------------------------------===//
13226586Sdim
14249423Sdim#include "clang/AST/ExprCXX.h"
15226586Sdim#include "clang/StaticAnalyzer/Core/CheckerManager.h"
16226586Sdim#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
17226586Sdim
18226586Sdimusing namespace clang;
19226586Sdimusing namespace ento;
20226586Sdimusing llvm::APSInt;
21226586Sdim
22226586Sdimvoid ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
23226586Sdim                                     ExplodedNode *Pred,
24226586Sdim                                     ExplodedNodeSet &Dst) {
25226586Sdim
26226586Sdim  Expr *LHS = B->getLHS()->IgnoreParens();
27226586Sdim  Expr *RHS = B->getRHS()->IgnoreParens();
28226586Sdim
29226586Sdim  // FIXME: Prechecks eventually go in ::Visit().
30226586Sdim  ExplodedNodeSet CheckedSet;
31226586Sdim  ExplodedNodeSet Tmp2;
32226586Sdim  getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this);
33226586Sdim
34226586Sdim  // With both the LHS and RHS evaluated, process the operation itself.
35226586Sdim  for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end();
36226586Sdim         it != ei; ++it) {
37226586Sdim
38234353Sdim    ProgramStateRef state = (*it)->getState();
39234353Sdim    const LocationContext *LCtx = (*it)->getLocationContext();
40234353Sdim    SVal LeftV = state->getSVal(LHS, LCtx);
41234353Sdim    SVal RightV = state->getSVal(RHS, LCtx);
42226586Sdim
43226586Sdim    BinaryOperator::Opcode Op = B->getOpcode();
44226586Sdim
45226586Sdim    if (Op == BO_Assign) {
46226586Sdim      // EXPERIMENTAL: "Conjured" symbols.
47226586Sdim      // FIXME: Handle structs.
48234353Sdim      if (RightV.isUnknown()) {
49243830Sdim        unsigned Count = currBldrCtx->blockCount();
50243830Sdim        RightV = svalBuilder.conjureSymbolVal(0, B->getRHS(), LCtx, Count);
51226586Sdim      }
52226586Sdim      // Simulate the effects of a "store":  bind the value of the RHS
53226586Sdim      // to the L-Value represented by the LHS.
54239462Sdim      SVal ExprVal = B->isGLValue() ? LeftV : RightV;
55234353Sdim      evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, LCtx, ExprVal),
56234353Sdim                LeftV, RightV);
57226586Sdim      continue;
58226586Sdim    }
59226586Sdim
60226586Sdim    if (!B->isAssignmentOp()) {
61243830Sdim      StmtNodeBuilder Bldr(*it, Tmp2, *currBldrCtx);
62239462Sdim
63239462Sdim      if (B->isAdditiveOp()) {
64239462Sdim        // If one of the operands is a location, conjure a symbol for the other
65239462Sdim        // one (offset) if it's unknown so that memory arithmetic always
66239462Sdim        // results in an ElementRegion.
67239462Sdim        // TODO: This can be removed after we enable history tracking with
68239462Sdim        // SymSymExpr.
69243830Sdim        unsigned Count = currBldrCtx->blockCount();
70249423Sdim        if (LeftV.getAs<Loc>() &&
71251662Sdim            RHS->getType()->isIntegralOrEnumerationType() &&
72251662Sdim            RightV.isUnknown()) {
73243830Sdim          RightV = svalBuilder.conjureSymbolVal(RHS, LCtx, RHS->getType(),
74243830Sdim                                                Count);
75239462Sdim        }
76249423Sdim        if (RightV.getAs<Loc>() &&
77251662Sdim            LHS->getType()->isIntegralOrEnumerationType() &&
78251662Sdim            LeftV.isUnknown()) {
79243830Sdim          LeftV = svalBuilder.conjureSymbolVal(LHS, LCtx, LHS->getType(),
80243830Sdim                                               Count);
81239462Sdim        }
82239462Sdim      }
83239462Sdim
84226586Sdim      // Process non-assignments except commas or short-circuited
85226586Sdim      // logical expressions (LAnd and LOr).
86226586Sdim      SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());
87226586Sdim      if (Result.isUnknown()) {
88234353Sdim        Bldr.generateNode(B, *it, state);
89226586Sdim        continue;
90226586Sdim      }
91226586Sdim
92234353Sdim      state = state->BindExpr(B, LCtx, Result);
93234353Sdim      Bldr.generateNode(B, *it, state);
94226586Sdim      continue;
95226586Sdim    }
96226586Sdim
97226586Sdim    assert (B->isCompoundAssignmentOp());
98226586Sdim
99226586Sdim    switch (Op) {
100226586Sdim      default:
101226586Sdim        llvm_unreachable("Invalid opcode for compound assignment.");
102226586Sdim      case BO_MulAssign: Op = BO_Mul; break;
103226586Sdim      case BO_DivAssign: Op = BO_Div; break;
104226586Sdim      case BO_RemAssign: Op = BO_Rem; break;
105226586Sdim      case BO_AddAssign: Op = BO_Add; break;
106226586Sdim      case BO_SubAssign: Op = BO_Sub; break;
107226586Sdim      case BO_ShlAssign: Op = BO_Shl; break;
108226586Sdim      case BO_ShrAssign: Op = BO_Shr; break;
109226586Sdim      case BO_AndAssign: Op = BO_And; break;
110226586Sdim      case BO_XorAssign: Op = BO_Xor; break;
111226586Sdim      case BO_OrAssign:  Op = BO_Or;  break;
112226586Sdim    }
113226586Sdim
114226586Sdim    // Perform a load (the LHS).  This performs the checks for
115226586Sdim    // null dereferences, and so on.
116226586Sdim    ExplodedNodeSet Tmp;
117226586Sdim    SVal location = LeftV;
118234353Sdim    evalLoad(Tmp, B, LHS, *it, state, location);
119226586Sdim
120226586Sdim    for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E;
121226586Sdim         ++I) {
122226586Sdim
123226586Sdim      state = (*I)->getState();
124234353Sdim      const LocationContext *LCtx = (*I)->getLocationContext();
125234353Sdim      SVal V = state->getSVal(LHS, LCtx);
126226586Sdim
127226586Sdim      // Get the computation type.
128226586Sdim      QualType CTy =
129226586Sdim        cast<CompoundAssignOperator>(B)->getComputationResultType();
130226586Sdim      CTy = getContext().getCanonicalType(CTy);
131226586Sdim
132226586Sdim      QualType CLHSTy =
133226586Sdim        cast<CompoundAssignOperator>(B)->getComputationLHSType();
134226586Sdim      CLHSTy = getContext().getCanonicalType(CLHSTy);
135226586Sdim
136226586Sdim      QualType LTy = getContext().getCanonicalType(LHS->getType());
137226586Sdim
138226586Sdim      // Promote LHS.
139226586Sdim      V = svalBuilder.evalCast(V, CLHSTy, LTy);
140226586Sdim
141226586Sdim      // Compute the result of the operation.
142226586Sdim      SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
143226586Sdim                                         B->getType(), CTy);
144226586Sdim
145226586Sdim      // EXPERIMENTAL: "Conjured" symbols.
146226586Sdim      // FIXME: Handle structs.
147226586Sdim
148226586Sdim      SVal LHSVal;
149226586Sdim
150234353Sdim      if (Result.isUnknown()) {
151226586Sdim        // The symbolic value is actually for the type of the left-hand side
152226586Sdim        // expression, not the computation type, as this is the value the
153226586Sdim        // LValue on the LHS will bind to.
154243830Sdim        LHSVal = svalBuilder.conjureSymbolVal(0, B->getRHS(), LCtx, LTy,
155243830Sdim                                              currBldrCtx->blockCount());
156226586Sdim        // However, we need to convert the symbol to the computation type.
157226586Sdim        Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
158226586Sdim      }
159226586Sdim      else {
160226586Sdim        // The left-hand side may bind to a different value then the
161226586Sdim        // computation type.
162226586Sdim        LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
163226586Sdim      }
164226586Sdim
165226586Sdim      // In C++, assignment and compound assignment operators return an
166226586Sdim      // lvalue.
167239462Sdim      if (B->isGLValue())
168234353Sdim        state = state->BindExpr(B, LCtx, location);
169226586Sdim      else
170234353Sdim        state = state->BindExpr(B, LCtx, Result);
171226586Sdim
172226586Sdim      evalStore(Tmp2, B, LHS, *I, state, location, LHSVal);
173226586Sdim    }
174226586Sdim  }
175226586Sdim
176226586Sdim  // FIXME: postvisits eventually go in ::Visit()
177226586Sdim  getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this);
178226586Sdim}
179226586Sdim
180226586Sdimvoid ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
181226586Sdim                                ExplodedNodeSet &Dst) {
182226586Sdim
183226586Sdim  CanQualType T = getContext().getCanonicalType(BE->getType());
184239462Sdim
185239462Sdim  // Get the value of the block itself.
186226586Sdim  SVal V = svalBuilder.getBlockPointer(BE->getBlockDecl(), T,
187263508Sdim                                       Pred->getLocationContext(),
188263508Sdim                                       currBldrCtx->blockCount());
189226586Sdim
190239462Sdim  ProgramStateRef State = Pred->getState();
191239462Sdim
192239462Sdim  // If we created a new MemRegion for the block, we should explicitly bind
193239462Sdim  // the captured variables.
194239462Sdim  if (const BlockDataRegion *BDR =
195239462Sdim      dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
196239462Sdim
197239462Sdim    BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
198239462Sdim                                              E = BDR->referenced_vars_end();
199239462Sdim
200239462Sdim    for (; I != E; ++I) {
201239462Sdim      const MemRegion *capturedR = I.getCapturedRegion();
202239462Sdim      const MemRegion *originalR = I.getOriginalRegion();
203239462Sdim      if (capturedR != originalR) {
204239462Sdim        SVal originalV = State->getSVal(loc::MemRegionVal(originalR));
205239462Sdim        State = State->bindLoc(loc::MemRegionVal(capturedR), originalV);
206239462Sdim      }
207239462Sdim    }
208239462Sdim  }
209239462Sdim
210226586Sdim  ExplodedNodeSet Tmp;
211243830Sdim  StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
212234353Sdim  Bldr.generateNode(BE, Pred,
213239462Sdim                    State->BindExpr(BE, Pred->getLocationContext(), V),
214243830Sdim                    0, ProgramPoint::PostLValueKind);
215226586Sdim
216226586Sdim  // FIXME: Move all post/pre visits to ::Visit().
217226586Sdim  getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
218226586Sdim}
219226586Sdim
220226586Sdimvoid ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
221226586Sdim                           ExplodedNode *Pred, ExplodedNodeSet &Dst) {
222226586Sdim
223226586Sdim  ExplodedNodeSet dstPreStmt;
224226586Sdim  getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this);
225226586Sdim
226234353Sdim  if (CastE->getCastKind() == CK_LValueToRValue) {
227226586Sdim    for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
228226586Sdim         I!=E; ++I) {
229226586Sdim      ExplodedNode *subExprNode = *I;
230234353Sdim      ProgramStateRef state = subExprNode->getState();
231234353Sdim      const LocationContext *LCtx = subExprNode->getLocationContext();
232234353Sdim      evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, LCtx));
233226586Sdim    }
234226586Sdim    return;
235226586Sdim  }
236226586Sdim
237226586Sdim  // All other casts.
238226586Sdim  QualType T = CastE->getType();
239226586Sdim  QualType ExTy = Ex->getType();
240226586Sdim
241226586Sdim  if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
242226586Sdim    T = ExCast->getTypeAsWritten();
243226586Sdim
244243830Sdim  StmtNodeBuilder Bldr(dstPreStmt, Dst, *currBldrCtx);
245226586Sdim  for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
246226586Sdim       I != E; ++I) {
247226586Sdim
248226586Sdim    Pred = *I;
249243830Sdim    ProgramStateRef state = Pred->getState();
250243830Sdim    const LocationContext *LCtx = Pred->getLocationContext();
251243830Sdim
252226586Sdim    switch (CastE->getCastKind()) {
253226586Sdim      case CK_LValueToRValue:
254226586Sdim        llvm_unreachable("LValueToRValue casts handled earlier.");
255226586Sdim      case CK_ToVoid:
256226586Sdim        continue;
257226586Sdim        // The analyzer doesn't do anything special with these casts,
258226586Sdim        // since it understands retain/release semantics already.
259226586Sdim      case CK_ARCProduceObject:
260226586Sdim      case CK_ARCConsumeObject:
261226586Sdim      case CK_ARCReclaimReturnedObject:
262226586Sdim      case CK_ARCExtendBlockObject: // Fall-through.
263234353Sdim      case CK_CopyAndAutoreleaseBlockObject:
264234353Sdim        // The analyser can ignore atomic casts for now, although some future
265234353Sdim        // checkers may want to make certain that you're not modifying the same
266234353Sdim        // value through atomic and nonatomic pointers.
267234353Sdim      case CK_AtomicToNonAtomic:
268234353Sdim      case CK_NonAtomicToAtomic:
269226586Sdim        // True no-ops.
270226586Sdim      case CK_NoOp:
271243830Sdim      case CK_ConstructorConversion:
272243830Sdim      case CK_UserDefinedConversion:
273243830Sdim      case CK_FunctionToPointerDecay:
274243830Sdim      case CK_BuiltinFnToFnPtr: {
275226586Sdim        // Copy the SVal of Ex to CastE.
276234353Sdim        ProgramStateRef state = Pred->getState();
277234353Sdim        const LocationContext *LCtx = Pred->getLocationContext();
278234353Sdim        SVal V = state->getSVal(Ex, LCtx);
279234353Sdim        state = state->BindExpr(CastE, LCtx, V);
280234353Sdim        Bldr.generateNode(CastE, Pred, state);
281226586Sdim        continue;
282226586Sdim      }
283243830Sdim      case CK_MemberPointerToBoolean:
284243830Sdim        // FIXME: For now, member pointers are represented by void *.
285243830Sdim        // FALLTHROUGH
286226586Sdim      case CK_Dependent:
287226586Sdim      case CK_ArrayToPointerDecay:
288226586Sdim      case CK_BitCast:
289226586Sdim      case CK_IntegralCast:
290226586Sdim      case CK_NullToPointer:
291226586Sdim      case CK_IntegralToPointer:
292226586Sdim      case CK_PointerToIntegral:
293226586Sdim      case CK_PointerToBoolean:
294226586Sdim      case CK_IntegralToBoolean:
295226586Sdim      case CK_IntegralToFloating:
296226586Sdim      case CK_FloatingToIntegral:
297226586Sdim      case CK_FloatingToBoolean:
298226586Sdim      case CK_FloatingCast:
299226586Sdim      case CK_FloatingRealToComplex:
300226586Sdim      case CK_FloatingComplexToReal:
301226586Sdim      case CK_FloatingComplexToBoolean:
302226586Sdim      case CK_FloatingComplexCast:
303226586Sdim      case CK_FloatingComplexToIntegralComplex:
304226586Sdim      case CK_IntegralRealToComplex:
305226586Sdim      case CK_IntegralComplexToReal:
306226586Sdim      case CK_IntegralComplexToBoolean:
307226586Sdim      case CK_IntegralComplexCast:
308226586Sdim      case CK_IntegralComplexToFloatingComplex:
309226586Sdim      case CK_CPointerToObjCPointerCast:
310226586Sdim      case CK_BlockPointerToObjCPointerCast:
311226586Sdim      case CK_AnyPointerToBlockPointerCast:
312249423Sdim      case CK_ObjCObjectLValueCast:
313263508Sdim      case CK_ZeroToOCLEvent:
314263508Sdim      case CK_LValueBitCast: {
315226586Sdim        // Delegate to SValBuilder to process.
316234353Sdim        SVal V = state->getSVal(Ex, LCtx);
317226586Sdim        V = svalBuilder.evalCast(V, T, ExTy);
318234353Sdim        state = state->BindExpr(CastE, LCtx, V);
319234353Sdim        Bldr.generateNode(CastE, Pred, state);
320226586Sdim        continue;
321226586Sdim      }
322226586Sdim      case CK_DerivedToBase:
323226586Sdim      case CK_UncheckedDerivedToBase: {
324226586Sdim        // For DerivedToBase cast, delegate to the store manager.
325234353Sdim        SVal val = state->getSVal(Ex, LCtx);
326239462Sdim        val = getStoreManager().evalDerivedToBase(val, CastE);
327234353Sdim        state = state->BindExpr(CastE, LCtx, val);
328234353Sdim        Bldr.generateNode(CastE, Pred, state);
329226586Sdim        continue;
330226586Sdim      }
331234353Sdim      // Handle C++ dyn_cast.
332234353Sdim      case CK_Dynamic: {
333234353Sdim        SVal val = state->getSVal(Ex, LCtx);
334234353Sdim
335234353Sdim        // Compute the type of the result.
336234353Sdim        QualType resultType = CastE->getType();
337239462Sdim        if (CastE->isGLValue())
338234353Sdim          resultType = getContext().getPointerType(resultType);
339234353Sdim
340234353Sdim        bool Failed = false;
341234353Sdim
342234353Sdim        // Check if the value being cast evaluates to 0.
343234353Sdim        if (val.isZeroConstant())
344234353Sdim          Failed = true;
345234353Sdim        // Else, evaluate the cast.
346234353Sdim        else
347234353Sdim          val = getStoreManager().evalDynamicCast(val, T, Failed);
348234353Sdim
349234353Sdim        if (Failed) {
350234353Sdim          if (T->isReferenceType()) {
351234353Sdim            // A bad_cast exception is thrown if input value is a reference.
352234353Sdim            // Currently, we model this, by generating a sink.
353243830Sdim            Bldr.generateSink(CastE, Pred, state);
354234353Sdim            continue;
355234353Sdim          } else {
356234353Sdim            // If the cast fails on a pointer, bind to 0.
357234353Sdim            state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull());
358234353Sdim          }
359234353Sdim        } else {
360234353Sdim          // If we don't know if the cast succeeded, conjure a new symbol.
361234353Sdim          if (val.isUnknown()) {
362243830Sdim            DefinedOrUnknownSVal NewSym =
363243830Sdim              svalBuilder.conjureSymbolVal(0, CastE, LCtx, resultType,
364243830Sdim                                           currBldrCtx->blockCount());
365234353Sdim            state = state->BindExpr(CastE, LCtx, NewSym);
366234353Sdim          } else
367234353Sdim            // Else, bind to the derived region value.
368234353Sdim            state = state->BindExpr(CastE, LCtx, val);
369234353Sdim        }
370234353Sdim        Bldr.generateNode(CastE, Pred, state);
371234353Sdim        continue;
372234353Sdim      }
373243830Sdim      case CK_NullToMemberPointer: {
374243830Sdim        // FIXME: For now, member pointers are represented by void *.
375263508Sdim        SVal V = svalBuilder.makeNull();
376243830Sdim        state = state->BindExpr(CastE, LCtx, V);
377243830Sdim        Bldr.generateNode(CastE, Pred, state);
378243830Sdim        continue;
379243830Sdim      }
380234353Sdim      // Various C++ casts that are not handled yet.
381226586Sdim      case CK_ToUnion:
382226586Sdim      case CK_BaseToDerived:
383226586Sdim      case CK_BaseToDerivedMemberPointer:
384226586Sdim      case CK_DerivedToBaseMemberPointer:
385234353Sdim      case CK_ReinterpretMemberPointer:
386263508Sdim      case CK_VectorSplat: {
387226586Sdim        // Recover some path-sensitivty by conjuring a new value.
388226586Sdim        QualType resultType = CastE->getType();
389239462Sdim        if (CastE->isGLValue())
390226586Sdim          resultType = getContext().getPointerType(resultType);
391243830Sdim        SVal result = svalBuilder.conjureSymbolVal(0, CastE, LCtx,
392243830Sdim                                                   resultType,
393243830Sdim                                                   currBldrCtx->blockCount());
394243830Sdim        state = state->BindExpr(CastE, LCtx, result);
395234353Sdim        Bldr.generateNode(CastE, Pred, state);
396226586Sdim        continue;
397226586Sdim      }
398226586Sdim    }
399226586Sdim  }
400226586Sdim}
401226586Sdim
402226586Sdimvoid ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
403226586Sdim                                          ExplodedNode *Pred,
404226586Sdim                                          ExplodedNodeSet &Dst) {
405243830Sdim  StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
406234353Sdim
407251662Sdim  ProgramStateRef State = Pred->getState();
408251662Sdim  const LocationContext *LCtx = Pred->getLocationContext();
409251662Sdim
410251662Sdim  const Expr *Init = CL->getInitializer();
411251662Sdim  SVal V = State->getSVal(CL->getInitializer(), LCtx);
412226586Sdim
413251662Sdim  if (isa<CXXConstructExpr>(Init)) {
414251662Sdim    // No work needed. Just pass the value up to this expression.
415251662Sdim  } else {
416251662Sdim    assert(isa<InitListExpr>(Init));
417251662Sdim    Loc CLLoc = State->getLValue(CL, LCtx);
418251662Sdim    State = State->bindLoc(CLLoc, V);
419239462Sdim
420251662Sdim    // Compound literal expressions are a GNU extension in C++.
421251662Sdim    // Unlike in C, where CLs are lvalues, in C++ CLs are prvalues,
422251662Sdim    // and like temporary objects created by the functional notation T()
423251662Sdim    // CLs are destroyed at the end of the containing full-expression.
424251662Sdim    // HOWEVER, an rvalue of array type is not something the analyzer can
425251662Sdim    // reason about, since we expect all regions to be wrapped in Locs.
426251662Sdim    // So we treat array CLs as lvalues as well, knowing that they will decay
427251662Sdim    // to pointers as soon as they are used.
428251662Sdim    if (CL->isGLValue() || CL->getType()->isArrayType())
429251662Sdim      V = CLLoc;
430251662Sdim  }
431251662Sdim
432251662Sdim  B.generateNode(CL, Pred, State->BindExpr(CL, LCtx, V));
433226586Sdim}
434226586Sdim
435226586Sdimvoid ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
436226586Sdim                               ExplodedNodeSet &Dst) {
437226586Sdim  // Assumption: The CFG has one DeclStmt per Decl.
438249423Sdim  const VarDecl *VD = dyn_cast_or_null<VarDecl>(*DS->decl_begin());
439249423Sdim
440249423Sdim  if (!VD) {
441234353Sdim    //TODO:AZ: remove explicit insertion after refactoring is done.
442234353Sdim    Dst.insert(Pred);
443226586Sdim    return;
444234353Sdim  }
445226586Sdim
446226586Sdim  // FIXME: all pre/post visits should eventually be handled by ::Visit().
447226586Sdim  ExplodedNodeSet dstPreVisit;
448226586Sdim  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
449226586Sdim
450263508Sdim  ExplodedNodeSet dstEvaluated;
451263508Sdim  StmtNodeBuilder B(dstPreVisit, dstEvaluated, *currBldrCtx);
452226586Sdim  for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
453226586Sdim       I!=E; ++I) {
454226586Sdim    ExplodedNode *N = *I;
455234353Sdim    ProgramStateRef state = N->getState();
456249423Sdim    const LocationContext *LC = N->getLocationContext();
457249423Sdim
458226586Sdim    // Decls without InitExpr are not initialized explicitly.
459226586Sdim    if (const Expr *InitEx = VD->getInit()) {
460249423Sdim
461249423Sdim      // Note in the state that the initialization has occurred.
462249423Sdim      ExplodedNode *UpdatedN = N;
463239462Sdim      SVal InitVal = state->getSVal(InitEx, LC);
464234353Sdim
465249423Sdim      if (isa<CXXConstructExpr>(InitEx->IgnoreImplicit())) {
466239462Sdim        // We constructed the object directly in the variable.
467239462Sdim        // No need to bind anything.
468249423Sdim        B.generateNode(DS, UpdatedN, state);
469239462Sdim      } else {
470239462Sdim        // We bound the temp obj region to the CXXConstructExpr. Now recover
471239462Sdim        // the lazy compound value when the variable is not a reference.
472249423Sdim        if (AMgr.getLangOpts().CPlusPlus && VD->getType()->isRecordType() &&
473249423Sdim            !VD->getType()->isReferenceType()) {
474249423Sdim          if (Optional<loc::MemRegionVal> M =
475249423Sdim                  InitVal.getAs<loc::MemRegionVal>()) {
476249423Sdim            InitVal = state->getSVal(M->getRegion());
477249423Sdim            assert(InitVal.getAs<nonloc::LazyCompoundVal>());
478249423Sdim          }
479239462Sdim        }
480239462Sdim
481239462Sdim        // Recover some path-sensitivity if a scalar value evaluated to
482239462Sdim        // UnknownVal.
483239462Sdim        if (InitVal.isUnknown()) {
484239462Sdim          QualType Ty = InitEx->getType();
485239462Sdim          if (InitEx->isGLValue()) {
486239462Sdim            Ty = getContext().getPointerType(Ty);
487239462Sdim          }
488239462Sdim
489243830Sdim          InitVal = svalBuilder.conjureSymbolVal(0, InitEx, LC, Ty,
490243830Sdim                                                 currBldrCtx->blockCount());
491239462Sdim        }
492249423Sdim
493249423Sdim
494249423Sdim        B.takeNodes(UpdatedN);
495239462Sdim        ExplodedNodeSet Dst2;
496249423Sdim        evalBind(Dst2, DS, UpdatedN, state->getLValue(VD, LC), InitVal, true);
497239462Sdim        B.addNodes(Dst2);
498226586Sdim      }
499226586Sdim    }
500226586Sdim    else {
501243830Sdim      B.generateNode(DS, N, state);
502226586Sdim    }
503226586Sdim  }
504263508Sdim
505263508Sdim  getCheckerManager().runCheckersForPostStmt(Dst, B.getResults(), DS, *this);
506226586Sdim}
507226586Sdim
508226586Sdimvoid ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
509226586Sdim                                  ExplodedNodeSet &Dst) {
510226586Sdim  assert(B->getOpcode() == BO_LAnd ||
511226586Sdim         B->getOpcode() == BO_LOr);
512234353Sdim
513243830Sdim  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
514234353Sdim  ProgramStateRef state = Pred->getState();
515239462Sdim
516239462Sdim  ExplodedNode *N = Pred;
517249423Sdim  while (!N->getLocation().getAs<BlockEntrance>()) {
518239462Sdim    ProgramPoint P = N->getLocation();
519249423Sdim    assert(P.getAs<PreStmt>()|| P.getAs<PreStmtPurgeDeadSymbols>());
520239462Sdim    (void) P;
521239462Sdim    assert(N->pred_size() == 1);
522239462Sdim    N = *N->pred_begin();
523226586Sdim  }
524239462Sdim  assert(N->pred_size() == 1);
525239462Sdim  N = *N->pred_begin();
526249423Sdim  BlockEdge BE = N->getLocation().castAs<BlockEdge>();
527239462Sdim  SVal X;
528239462Sdim
529239462Sdim  // Determine the value of the expression by introspecting how we
530239462Sdim  // got this location in the CFG.  This requires looking at the previous
531239462Sdim  // block we were in and what kind of control-flow transfer was involved.
532239462Sdim  const CFGBlock *SrcBlock = BE.getSrc();
533239462Sdim  // The only terminator (if there is one) that makes sense is a logical op.
534239462Sdim  CFGTerminator T = SrcBlock->getTerminator();
535239462Sdim  if (const BinaryOperator *Term = cast_or_null<BinaryOperator>(T.getStmt())) {
536239462Sdim    (void) Term;
537239462Sdim    assert(Term->isLogicalOp());
538239462Sdim    assert(SrcBlock->succ_size() == 2);
539239462Sdim    // Did we take the true or false branch?
540239462Sdim    unsigned constant = (*SrcBlock->succ_begin() == BE.getDst()) ? 1 : 0;
541239462Sdim    X = svalBuilder.makeIntVal(constant, B->getType());
542239462Sdim  }
543226586Sdim  else {
544239462Sdim    // If there is no terminator, by construction the last statement
545239462Sdim    // in SrcBlock is the value of the enclosing expression.
546243830Sdim    // However, we still need to constrain that value to be 0 or 1.
547239462Sdim    assert(!SrcBlock->empty());
548249423Sdim    CFGStmt Elem = SrcBlock->rbegin()->castAs<CFGStmt>();
549243830Sdim    const Expr *RHS = cast<Expr>(Elem.getStmt());
550243830Sdim    SVal RHSVal = N->getState()->getSVal(RHS, Pred->getLocationContext());
551243830Sdim
552249423Sdim    if (RHSVal.isUndef()) {
553249423Sdim      X = RHSVal;
554249423Sdim    } else {
555249423Sdim      DefinedOrUnknownSVal DefinedRHS = RHSVal.castAs<DefinedOrUnknownSVal>();
556249423Sdim      ProgramStateRef StTrue, StFalse;
557249423Sdim      llvm::tie(StTrue, StFalse) = N->getState()->assume(DefinedRHS);
558249423Sdim      if (StTrue) {
559249423Sdim        if (StFalse) {
560249423Sdim          // We can't constrain the value to 0 or 1.
561249423Sdim          // The best we can do is a cast.
562249423Sdim          X = getSValBuilder().evalCast(RHSVal, B->getType(), RHS->getType());
563249423Sdim        } else {
564249423Sdim          // The value is known to be true.
565249423Sdim          X = getSValBuilder().makeIntVal(1, B->getType());
566249423Sdim        }
567243830Sdim      } else {
568249423Sdim        // The value is known to be false.
569249423Sdim        assert(StFalse && "Infeasible path!");
570249423Sdim        X = getSValBuilder().makeIntVal(0, B->getType());
571243830Sdim      }
572243830Sdim    }
573226586Sdim  }
574239462Sdim  Bldr.generateNode(B, Pred, state->BindExpr(B, Pred->getLocationContext(), X));
575226586Sdim}
576226586Sdim
577226586Sdimvoid ExprEngine::VisitInitListExpr(const InitListExpr *IE,
578226586Sdim                                   ExplodedNode *Pred,
579226586Sdim                                   ExplodedNodeSet &Dst) {
580243830Sdim  StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
581226586Sdim
582234353Sdim  ProgramStateRef state = Pred->getState();
583234353Sdim  const LocationContext *LCtx = Pred->getLocationContext();
584226586Sdim  QualType T = getContext().getCanonicalType(IE->getType());
585226586Sdim  unsigned NumInitElements = IE->getNumInits();
586263508Sdim
587263508Sdim  if (!IE->isGLValue() &&
588263508Sdim      (T->isArrayType() || T->isRecordType() || T->isVectorType() ||
589263508Sdim       T->isAnyComplexType())) {
590226586Sdim    llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
591226586Sdim
592226586Sdim    // Handle base case where the initializer has no elements.
593226586Sdim    // e.g: static int* myArray[] = {};
594226586Sdim    if (NumInitElements == 0) {
595226586Sdim      SVal V = svalBuilder.makeCompoundVal(T, vals);
596234353Sdim      B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
597226586Sdim      return;
598226586Sdim    }
599226586Sdim
600226586Sdim    for (InitListExpr::const_reverse_iterator it = IE->rbegin(),
601226586Sdim         ei = IE->rend(); it != ei; ++it) {
602249423Sdim      SVal V = state->getSVal(cast<Expr>(*it), LCtx);
603249423Sdim      vals = getBasicVals().consVals(V, vals);
604226586Sdim    }
605226586Sdim
606234353Sdim    B.generateNode(IE, Pred,
607234353Sdim                   state->BindExpr(IE, LCtx,
608234353Sdim                                   svalBuilder.makeCompoundVal(T, vals)));
609226586Sdim    return;
610226586Sdim  }
611239462Sdim
612263508Sdim  // Handle scalars: int{5} and int{} and GLvalues.
613263508Sdim  // Note, if the InitListExpr is a GLvalue, it means that there is an address
614263508Sdim  // representing it, so it must have a single init element.
615239462Sdim  assert(NumInitElements <= 1);
616239462Sdim
617239462Sdim  SVal V;
618239462Sdim  if (NumInitElements == 0)
619239462Sdim    V = getSValBuilder().makeZeroVal(T);
620239462Sdim  else
621239462Sdim    V = state->getSVal(IE->getInit(0), LCtx);
622239462Sdim
623239462Sdim  B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
624226586Sdim}
625226586Sdim
626226586Sdimvoid ExprEngine::VisitGuardedExpr(const Expr *Ex,
627226586Sdim                                  const Expr *L,
628226586Sdim                                  const Expr *R,
629226586Sdim                                  ExplodedNode *Pred,
630226586Sdim                                  ExplodedNodeSet &Dst) {
631251662Sdim  assert(L && R);
632251662Sdim
633243830Sdim  StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
634234353Sdim  ProgramStateRef state = Pred->getState();
635234353Sdim  const LocationContext *LCtx = Pred->getLocationContext();
636239462Sdim  const CFGBlock *SrcBlock = 0;
637239462Sdim
638251662Sdim  // Find the predecessor block.
639251662Sdim  ProgramStateRef SrcState = state;
640239462Sdim  for (const ExplodedNode *N = Pred ; N ; N = *N->pred_begin()) {
641239462Sdim    ProgramPoint PP = N->getLocation();
642249423Sdim    if (PP.getAs<PreStmtPurgeDeadSymbols>() || PP.getAs<BlockEntrance>()) {
643239462Sdim      assert(N->pred_size() == 1);
644239462Sdim      continue;
645239462Sdim    }
646249423Sdim    SrcBlock = PP.castAs<BlockEdge>().getSrc();
647251662Sdim    SrcState = N->getState();
648239462Sdim    break;
649239462Sdim  }
650239462Sdim
651249423Sdim  assert(SrcBlock && "missing function entry");
652249423Sdim
653239462Sdim  // Find the last expression in the predecessor block.  That is the
654239462Sdim  // expression that is used for the value of the ternary expression.
655239462Sdim  bool hasValue = false;
656239462Sdim  SVal V;
657239462Sdim
658239462Sdim  for (CFGBlock::const_reverse_iterator I = SrcBlock->rbegin(),
659239462Sdim                                        E = SrcBlock->rend(); I != E; ++I) {
660239462Sdim    CFGElement CE = *I;
661249423Sdim    if (Optional<CFGStmt> CS = CE.getAs<CFGStmt>()) {
662239462Sdim      const Expr *ValEx = cast<Expr>(CS->getStmt());
663251662Sdim      ValEx = ValEx->IgnoreParens();
664251662Sdim
665251662Sdim      // For GNU extension '?:' operator, the left hand side will be an
666251662Sdim      // OpaqueValueExpr, so get the underlying expression.
667251662Sdim      if (const OpaqueValueExpr *OpaqueEx = dyn_cast<OpaqueValueExpr>(L))
668251662Sdim        L = OpaqueEx->getSourceExpr();
669251662Sdim
670251662Sdim      // If the last expression in the predecessor block matches true or false
671251662Sdim      // subexpression, get its the value.
672251662Sdim      if (ValEx == L->IgnoreParens() || ValEx == R->IgnoreParens()) {
673251662Sdim        hasValue = true;
674251662Sdim        V = SrcState->getSVal(ValEx, LCtx);
675251662Sdim      }
676239462Sdim      break;
677239462Sdim    }
678239462Sdim  }
679239462Sdim
680251662Sdim  if (!hasValue)
681251662Sdim    V = svalBuilder.conjureSymbolVal(0, Ex, LCtx, currBldrCtx->blockCount());
682239462Sdim
683239462Sdim  // Generate a new node with the binding from the appropriate path.
684239462Sdim  B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true));
685226586Sdim}
686226586Sdim
687226586Sdimvoid ExprEngine::
688226586SdimVisitOffsetOfExpr(const OffsetOfExpr *OOE,
689226586Sdim                  ExplodedNode *Pred, ExplodedNodeSet &Dst) {
690243830Sdim  StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
691234353Sdim  APSInt IV;
692234353Sdim  if (OOE->EvaluateAsInt(IV, getContext())) {
693226586Sdim    assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
694251662Sdim    assert(OOE->getType()->isBuiltinType());
695251662Sdim    assert(OOE->getType()->getAs<BuiltinType>()->isInteger());
696251662Sdim    assert(IV.isSigned() == OOE->getType()->isSignedIntegerType());
697226586Sdim    SVal X = svalBuilder.makeIntVal(IV);
698234353Sdim    B.generateNode(OOE, Pred,
699234353Sdim                   Pred->getState()->BindExpr(OOE, Pred->getLocationContext(),
700234353Sdim                                              X));
701226586Sdim  }
702226586Sdim  // FIXME: Handle the case where __builtin_offsetof is not a constant.
703226586Sdim}
704226586Sdim
705226586Sdim
706226586Sdimvoid ExprEngine::
707226586SdimVisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
708226586Sdim                              ExplodedNode *Pred,
709226586Sdim                              ExplodedNodeSet &Dst) {
710243830Sdim  StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
711226586Sdim
712226586Sdim  QualType T = Ex->getTypeOfArgument();
713226586Sdim
714226586Sdim  if (Ex->getKind() == UETT_SizeOf) {
715226586Sdim    if (!T->isIncompleteType() && !T->isConstantSizeType()) {
716226586Sdim      assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
717226586Sdim
718226586Sdim      // FIXME: Add support for VLA type arguments and VLA expressions.
719226586Sdim      // When that happens, we should probably refactor VLASizeChecker's code.
720226586Sdim      return;
721226586Sdim    }
722226586Sdim    else if (T->getAs<ObjCObjectType>()) {
723226586Sdim      // Some code tries to take the sizeof an ObjCObjectType, relying that
724226586Sdim      // the compiler has laid out its representation.  Just report Unknown
725226586Sdim      // for these.
726226586Sdim      return;
727226586Sdim    }
728226586Sdim  }
729226586Sdim
730234353Sdim  APSInt Value = Ex->EvaluateKnownConstInt(getContext());
731234353Sdim  CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
732226586Sdim
733234353Sdim  ProgramStateRef state = Pred->getState();
734234353Sdim  state = state->BindExpr(Ex, Pred->getLocationContext(),
735234353Sdim                          svalBuilder.makeIntVal(amt.getQuantity(),
736226586Sdim                                                     Ex->getType()));
737234353Sdim  Bldr.generateNode(Ex, Pred, state);
738226586Sdim}
739226586Sdim
740226586Sdimvoid ExprEngine::VisitUnaryOperator(const UnaryOperator* U,
741226586Sdim                                    ExplodedNode *Pred,
742234353Sdim                                    ExplodedNodeSet &Dst) {
743263508Sdim  // FIXME: Prechecks eventually go in ::Visit().
744263508Sdim  ExplodedNodeSet CheckedSet;
745263508Sdim  getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, U, *this);
746263508Sdim
747263508Sdim  ExplodedNodeSet EvalSet;
748263508Sdim  StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
749263508Sdim
750263508Sdim  for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
751263508Sdim       I != E; ++I) {
752263508Sdim    switch (U->getOpcode()) {
753234353Sdim    default: {
754263508Sdim      Bldr.takeNodes(*I);
755234353Sdim      ExplodedNodeSet Tmp;
756263508Sdim      VisitIncrementDecrementOperator(U, *I, Tmp);
757234353Sdim      Bldr.addNodes(Tmp);
758263508Sdim      break;
759234353Sdim    }
760226586Sdim    case UO_Real: {
761226586Sdim      const Expr *Ex = U->getSubExpr()->IgnoreParens();
762226586Sdim
763234353Sdim      // FIXME: We don't have complex SValues yet.
764234353Sdim      if (Ex->getType()->isAnyComplexType()) {
765234353Sdim        // Just report "Unknown."
766234353Sdim        break;
767234353Sdim      }
768226586Sdim
769234353Sdim      // For all other types, UO_Real is an identity operation.
770234353Sdim      assert (U->getType() == Ex->getType());
771263508Sdim      ProgramStateRef state = (*I)->getState();
772263508Sdim      const LocationContext *LCtx = (*I)->getLocationContext();
773263508Sdim      Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
774263508Sdim                                               state->getSVal(Ex, LCtx)));
775234353Sdim      break;
776226586Sdim    }
777226586Sdim
778234353Sdim    case UO_Imag: {
779226586Sdim      const Expr *Ex = U->getSubExpr()->IgnoreParens();
780234353Sdim      // FIXME: We don't have complex SValues yet.
781234353Sdim      if (Ex->getType()->isAnyComplexType()) {
782234353Sdim        // Just report "Unknown."
783234353Sdim        break;
784226586Sdim      }
785234353Sdim      // For all other types, UO_Imag returns 0.
786263508Sdim      ProgramStateRef state = (*I)->getState();
787263508Sdim      const LocationContext *LCtx = (*I)->getLocationContext();
788234353Sdim      SVal X = svalBuilder.makeZeroVal(Ex->getType());
789263508Sdim      Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, X));
790234353Sdim      break;
791226586Sdim    }
792226586Sdim
793226586Sdim    case UO_Plus:
794239462Sdim      assert(!U->isGLValue());
795226586Sdim      // FALL-THROUGH.
796226586Sdim    case UO_Deref:
797226586Sdim    case UO_AddrOf:
798226586Sdim    case UO_Extension: {
799234353Sdim      // FIXME: We can probably just have some magic in Environment::getSVal()
800234353Sdim      // that propagates values, instead of creating a new node here.
801234353Sdim      //
802226586Sdim      // Unary "+" is a no-op, similar to a parentheses.  We still have places
803226586Sdim      // where it may be a block-level expression, so we need to
804226586Sdim      // generate an extra node that just propagates the value of the
805234353Sdim      // subexpression.
806226586Sdim      const Expr *Ex = U->getSubExpr()->IgnoreParens();
807263508Sdim      ProgramStateRef state = (*I)->getState();
808263508Sdim      const LocationContext *LCtx = (*I)->getLocationContext();
809263508Sdim      Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
810263508Sdim                                               state->getSVal(Ex, LCtx)));
811234353Sdim      break;
812226586Sdim    }
813226586Sdim
814226586Sdim    case UO_LNot:
815226586Sdim    case UO_Minus:
816226586Sdim    case UO_Not: {
817239462Sdim      assert (!U->isGLValue());
818226586Sdim      const Expr *Ex = U->getSubExpr()->IgnoreParens();
819263508Sdim      ProgramStateRef state = (*I)->getState();
820263508Sdim      const LocationContext *LCtx = (*I)->getLocationContext();
821226586Sdim
822234353Sdim      // Get the value of the subexpression.
823234353Sdim      SVal V = state->getSVal(Ex, LCtx);
824226586Sdim
825234353Sdim      if (V.isUnknownOrUndef()) {
826263508Sdim        Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V));
827234353Sdim        break;
828234353Sdim      }
829226586Sdim
830234353Sdim      switch (U->getOpcode()) {
831234353Sdim        default:
832234353Sdim          llvm_unreachable("Invalid Opcode.");
833234353Sdim        case UO_Not:
834234353Sdim          // FIXME: Do we need to handle promotions?
835249423Sdim          state = state->BindExpr(U, LCtx, evalComplement(V.castAs<NonLoc>()));
836234353Sdim          break;
837234353Sdim        case UO_Minus:
838234353Sdim          // FIXME: Do we need to handle promotions?
839249423Sdim          state = state->BindExpr(U, LCtx, evalMinus(V.castAs<NonLoc>()));
840234353Sdim          break;
841234353Sdim        case UO_LNot:
842234353Sdim          // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
843234353Sdim          //
844234353Sdim          //  Note: technically we do "E == 0", but this is the same in the
845234353Sdim          //    transfer functions as "0 == E".
846234353Sdim          SVal Result;
847249423Sdim          if (Optional<Loc> LV = V.getAs<Loc>()) {
848234353Sdim            Loc X = svalBuilder.makeNull();
849249423Sdim            Result = evalBinOp(state, BO_EQ, *LV, X, U->getType());
850234353Sdim          }
851249423Sdim          else if (Ex->getType()->isFloatingType()) {
852249423Sdim            // FIXME: handle floating point types.
853249423Sdim            Result = UnknownVal();
854249423Sdim          } else {
855234353Sdim            nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
856249423Sdim            Result = evalBinOp(state, BO_EQ, V.castAs<NonLoc>(), X,
857234353Sdim                               U->getType());
858234353Sdim          }
859234353Sdim
860234353Sdim          state = state->BindExpr(U, LCtx, Result);
861234353Sdim          break;
862226586Sdim      }
863263508Sdim      Bldr.generateNode(U, *I, state);
864234353Sdim      break;
865226586Sdim    }
866263508Sdim    }
867226586Sdim  }
868234353Sdim
869263508Sdim  getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, U, *this);
870234353Sdim}
871234353Sdim
872234353Sdimvoid ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
873234353Sdim                                                 ExplodedNode *Pred,
874234353Sdim                                                 ExplodedNodeSet &Dst) {
875226586Sdim  // Handle ++ and -- (both pre- and post-increment).
876226586Sdim  assert (U->isIncrementDecrementOp());
877226586Sdim  const Expr *Ex = U->getSubExpr()->IgnoreParens();
878226586Sdim
879234353Sdim  const LocationContext *LCtx = Pred->getLocationContext();
880234353Sdim  ProgramStateRef state = Pred->getState();
881234353Sdim  SVal loc = state->getSVal(Ex, LCtx);
882234353Sdim
883234353Sdim  // Perform a load.
884234353Sdim  ExplodedNodeSet Tmp;
885234353Sdim  evalLoad(Tmp, U, Ex, Pred, state, loc);
886234353Sdim
887234353Sdim  ExplodedNodeSet Dst2;
888243830Sdim  StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx);
889234353Sdim  for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) {
890226586Sdim
891234353Sdim    state = (*I)->getState();
892234353Sdim    assert(LCtx == (*I)->getLocationContext());
893234353Sdim    SVal V2_untested = state->getSVal(Ex, LCtx);
894226586Sdim
895234353Sdim    // Propagate unknown and undefined values.
896234353Sdim    if (V2_untested.isUnknownOrUndef()) {
897234353Sdim      Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V2_untested));
898234353Sdim      continue;
899234353Sdim    }
900249423Sdim    DefinedSVal V2 = V2_untested.castAs<DefinedSVal>();
901226586Sdim
902234353Sdim    // Handle all other values.
903234353Sdim    BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub;
904234353Sdim
905234353Sdim    // If the UnaryOperator has non-location type, use its type to create the
906234353Sdim    // constant value. If the UnaryOperator has location type, create the
907234353Sdim    // constant with int type and pointer width.
908234353Sdim    SVal RHS;
909234353Sdim
910234353Sdim    if (U->getType()->isAnyPointerType())
911234353Sdim      RHS = svalBuilder.makeArrayIndex(1);
912243830Sdim    else if (U->getType()->isIntegralOrEnumerationType())
913243830Sdim      RHS = svalBuilder.makeIntVal(1, U->getType());
914234353Sdim    else
915243830Sdim      RHS = UnknownVal();
916234353Sdim
917234353Sdim    SVal Result = evalBinOp(state, Op, V2, RHS, U->getType());
918234353Sdim
919234353Sdim    // Conjure a new symbol if necessary to recover precision.
920234353Sdim    if (Result.isUnknown()){
921234353Sdim      DefinedOrUnknownSVal SymVal =
922243830Sdim        svalBuilder.conjureSymbolVal(0, Ex, LCtx, currBldrCtx->blockCount());
923234353Sdim      Result = SymVal;
924226586Sdim
925234353Sdim      // If the value is a location, ++/-- should always preserve
926234353Sdim      // non-nullness.  Check if the original value was non-null, and if so
927234353Sdim      // propagate that constraint.
928234353Sdim      if (Loc::isLocType(U->getType())) {
929234353Sdim        DefinedOrUnknownSVal Constraint =
930234353Sdim        svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
931226586Sdim
932234353Sdim        if (!state->assume(Constraint, true)) {
933234353Sdim          // It isn't feasible for the original value to be null.
934234353Sdim          // Propagate this constraint.
935234353Sdim          Constraint = svalBuilder.evalEQ(state, SymVal,
936234353Sdim                                       svalBuilder.makeZeroVal(U->getType()));
937226586Sdim
938234353Sdim
939234353Sdim          state = state->assume(Constraint, false);
940234353Sdim          assert(state);
941226586Sdim        }
942226586Sdim      }
943226586Sdim    }
944234353Sdim
945234353Sdim    // Since the lvalue-to-rvalue conversion is explicit in the AST,
946234353Sdim    // we bind an l-value if the operator is prefix and an lvalue (in C++).
947239462Sdim    if (U->isGLValue())
948234353Sdim      state = state->BindExpr(U, LCtx, loc);
949234353Sdim    else
950234353Sdim      state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result);
951234353Sdim
952234353Sdim    // Perform the store.
953234353Sdim    Bldr.takeNodes(*I);
954234353Sdim    ExplodedNodeSet Dst3;
955234353Sdim    evalStore(Dst3, U, U, *I, state, loc, Result);
956234353Sdim    Bldr.addNodes(Dst3);
957226586Sdim  }
958234353Sdim  Dst.insert(Dst2);
959226586Sdim}
960