ExprEngineC.cpp revision aa0aeb1cbe117db68d35700cb3a34aace0f99b99
1//=-- ExprEngineC.cpp - ExprEngine support for C expressions ----*- 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 ExprEngine's support for C expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/StaticAnalyzer/Core/CheckerManager.h"
15#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
16#include "clang/Analysis/Support/SaveAndRestore.h"
17
18using namespace clang;
19using namespace ento;
20using llvm::APSInt;
21
22void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
23                                     ExplodedNode *Pred,
24                                     ExplodedNodeSet &Dst) {
25
26  Expr *LHS = B->getLHS()->IgnoreParens();
27  Expr *RHS = B->getRHS()->IgnoreParens();
28
29  // FIXME: Prechecks eventually go in ::Visit().
30  ExplodedNodeSet CheckedSet;
31  ExplodedNodeSet Tmp2;
32  getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this);
33
34  // With both the LHS and RHS evaluated, process the operation itself.
35  for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end();
36         it != ei; ++it) {
37
38    const ProgramState *state = (*it)->getState();
39    SVal LeftV = state->getSVal(LHS);
40    SVal RightV = state->getSVal(RHS);
41
42    BinaryOperator::Opcode Op = B->getOpcode();
43
44    if (Op == BO_Assign) {
45      // EXPERIMENTAL: "Conjured" symbols.
46      // FIXME: Handle structs.
47      if (RightV.isUnknown() ||
48          !getConstraintManager().canReasonAbout(RightV)) {
49        unsigned Count = currentBuilderContext->getCurrentBlockCount();
50        RightV = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), Count);
51      }
52      // Simulate the effects of a "store":  bind the value of the RHS
53      // to the L-Value represented by the LHS.
54      SVal ExprVal = B->isLValue() ? LeftV : RightV;
55      evalStore(Tmp2, B, LHS, *it, state->BindExpr(B, ExprVal), LeftV, RightV);
56      continue;
57    }
58
59    if (!B->isAssignmentOp()) {
60      StmtNodeBuilder Bldr(*it, Tmp2, *currentBuilderContext);
61      // Process non-assignments except commas or short-circuited
62      // logical expressions (LAnd and LOr).
63      SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());
64      if (Result.isUnknown()) {
65        Bldr.generateNode(B, *it, state);
66        continue;
67      }
68
69      state = state->BindExpr(B, Result);
70      Bldr.generateNode(B, *it, state);
71      continue;
72    }
73
74    assert (B->isCompoundAssignmentOp());
75
76    switch (Op) {
77      default:
78        llvm_unreachable("Invalid opcode for compound assignment.");
79      case BO_MulAssign: Op = BO_Mul; break;
80      case BO_DivAssign: Op = BO_Div; break;
81      case BO_RemAssign: Op = BO_Rem; break;
82      case BO_AddAssign: Op = BO_Add; break;
83      case BO_SubAssign: Op = BO_Sub; break;
84      case BO_ShlAssign: Op = BO_Shl; break;
85      case BO_ShrAssign: Op = BO_Shr; break;
86      case BO_AndAssign: Op = BO_And; break;
87      case BO_XorAssign: Op = BO_Xor; break;
88      case BO_OrAssign:  Op = BO_Or;  break;
89    }
90
91    // Perform a load (the LHS).  This performs the checks for
92    // null dereferences, and so on.
93    ExplodedNodeSet Tmp;
94    SVal location = LeftV;
95    evalLoad(Tmp, LHS, *it, state, location);
96
97    for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E;
98         ++I) {
99
100      state = (*I)->getState();
101      SVal V = state->getSVal(LHS);
102
103      // Get the computation type.
104      QualType CTy =
105        cast<CompoundAssignOperator>(B)->getComputationResultType();
106      CTy = getContext().getCanonicalType(CTy);
107
108      QualType CLHSTy =
109        cast<CompoundAssignOperator>(B)->getComputationLHSType();
110      CLHSTy = getContext().getCanonicalType(CLHSTy);
111
112      QualType LTy = getContext().getCanonicalType(LHS->getType());
113
114      // Promote LHS.
115      V = svalBuilder.evalCast(V, CLHSTy, LTy);
116
117      // Compute the result of the operation.
118      SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
119                                         B->getType(), CTy);
120
121      // EXPERIMENTAL: "Conjured" symbols.
122      // FIXME: Handle structs.
123
124      SVal LHSVal;
125
126      if (Result.isUnknown() ||
127          !getConstraintManager().canReasonAbout(Result)) {
128
129        unsigned Count = currentBuilderContext->getCurrentBlockCount();
130
131        // The symbolic value is actually for the type of the left-hand side
132        // expression, not the computation type, as this is the value the
133        // LValue on the LHS will bind to.
134        LHSVal = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), LTy,
135                                                  Count);
136
137        // However, we need to convert the symbol to the computation type.
138        Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
139      }
140      else {
141        // The left-hand side may bind to a different value then the
142        // computation type.
143        LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
144      }
145
146      // In C++, assignment and compound assignment operators return an
147      // lvalue.
148      if (B->isLValue())
149        state = state->BindExpr(B, location);
150      else
151        state = state->BindExpr(B, Result);
152
153      evalStore(Tmp2, B, LHS, *I, state, location, LHSVal);
154    }
155  }
156
157  // FIXME: postvisits eventually go in ::Visit()
158  getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this);
159}
160
161void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
162                                ExplodedNodeSet &Dst) {
163
164  CanQualType T = getContext().getCanonicalType(BE->getType());
165  SVal V = svalBuilder.getBlockPointer(BE->getBlockDecl(), T,
166                                       Pred->getLocationContext());
167
168  ExplodedNodeSet Tmp;
169  StmtNodeBuilder Bldr(Pred, Tmp, *currentBuilderContext);
170  Bldr.generateNode(BE, Pred, Pred->getState()->BindExpr(BE, V), false, 0,
171                    ProgramPoint::PostLValueKind);
172
173  // FIXME: Move all post/pre visits to ::Visit().
174  getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
175}
176
177void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
178                           ExplodedNode *Pred, ExplodedNodeSet &Dst) {
179
180  ExplodedNodeSet dstPreStmt;
181  getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this);
182
183  if (CastE->getCastKind() == CK_LValueToRValue ||
184      CastE->getCastKind() == CK_GetObjCProperty) {
185    for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
186         I!=E; ++I) {
187      ExplodedNode *subExprNode = *I;
188      const ProgramState *state = subExprNode->getState();
189      evalLoad(Dst, CastE, subExprNode, state, state->getSVal(Ex));
190    }
191    return;
192  }
193
194  // All other casts.
195  QualType T = CastE->getType();
196  QualType ExTy = Ex->getType();
197
198  if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
199    T = ExCast->getTypeAsWritten();
200
201  StmtNodeBuilder Bldr(dstPreStmt, Dst, *currentBuilderContext);
202  for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
203       I != E; ++I) {
204
205    Pred = *I;
206
207    switch (CastE->getCastKind()) {
208      case CK_LValueToRValue:
209        llvm_unreachable("LValueToRValue casts handled earlier.");
210      case CK_GetObjCProperty:
211        llvm_unreachable("GetObjCProperty casts handled earlier.");
212      case CK_ToVoid:
213        continue;
214        // The analyzer doesn't do anything special with these casts,
215        // since it understands retain/release semantics already.
216      case CK_ARCProduceObject:
217      case CK_ARCConsumeObject:
218      case CK_ARCReclaimReturnedObject:
219      case CK_ARCExtendBlockObject: // Fall-through.
220        // True no-ops.
221      case CK_NoOp:
222      case CK_FunctionToPointerDecay: {
223        // Copy the SVal of Ex to CastE.
224        const ProgramState *state = Pred->getState();
225        SVal V = state->getSVal(Ex);
226        state = state->BindExpr(CastE, V);
227        Bldr.generateNode(CastE, Pred, state);
228        continue;
229      }
230      case CK_Dependent:
231      case CK_ArrayToPointerDecay:
232      case CK_BitCast:
233      case CK_LValueBitCast:
234      case CK_IntegralCast:
235      case CK_NullToPointer:
236      case CK_IntegralToPointer:
237      case CK_PointerToIntegral:
238      case CK_PointerToBoolean:
239      case CK_IntegralToBoolean:
240      case CK_IntegralToFloating:
241      case CK_FloatingToIntegral:
242      case CK_FloatingToBoolean:
243      case CK_FloatingCast:
244      case CK_FloatingRealToComplex:
245      case CK_FloatingComplexToReal:
246      case CK_FloatingComplexToBoolean:
247      case CK_FloatingComplexCast:
248      case CK_FloatingComplexToIntegralComplex:
249      case CK_IntegralRealToComplex:
250      case CK_IntegralComplexToReal:
251      case CK_IntegralComplexToBoolean:
252      case CK_IntegralComplexCast:
253      case CK_IntegralComplexToFloatingComplex:
254      case CK_CPointerToObjCPointerCast:
255      case CK_BlockPointerToObjCPointerCast:
256      case CK_AnyPointerToBlockPointerCast:
257      case CK_ObjCObjectLValueCast: {
258        // Delegate to SValBuilder to process.
259        const ProgramState *state = Pred->getState();
260        SVal V = state->getSVal(Ex);
261        V = svalBuilder.evalCast(V, T, ExTy);
262        state = state->BindExpr(CastE, V);
263        Bldr.generateNode(CastE, Pred, state);
264        continue;
265      }
266      case CK_DerivedToBase:
267      case CK_UncheckedDerivedToBase: {
268        // For DerivedToBase cast, delegate to the store manager.
269        const ProgramState *state = Pred->getState();
270        SVal val = state->getSVal(Ex);
271        val = getStoreManager().evalDerivedToBase(val, T);
272        state = state->BindExpr(CastE, val);
273        Bldr.generateNode(CastE, Pred, state);
274        continue;
275      }
276        // Various C++ casts that are not handled yet.
277      case CK_Dynamic:
278      case CK_ToUnion:
279      case CK_BaseToDerived:
280      case CK_NullToMemberPointer:
281      case CK_BaseToDerivedMemberPointer:
282      case CK_DerivedToBaseMemberPointer:
283      case CK_UserDefinedConversion:
284      case CK_ConstructorConversion:
285      case CK_VectorSplat:
286      case CK_MemberPointerToBoolean: {
287        // Recover some path-sensitivty by conjuring a new value.
288        QualType resultType = CastE->getType();
289        if (CastE->isLValue())
290          resultType = getContext().getPointerType(resultType);
291
292        SVal result =
293        svalBuilder.getConjuredSymbolVal(NULL, CastE, resultType,
294                               currentBuilderContext->getCurrentBlockCount());
295
296        const ProgramState *state = Pred->getState()->BindExpr(CastE, result);
297        Bldr.generateNode(CastE, Pred, state);
298        continue;
299      }
300    }
301  }
302}
303
304void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
305                                          ExplodedNode *Pred,
306                                          ExplodedNodeSet &Dst) {
307  StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
308
309  const InitListExpr *ILE
310    = cast<InitListExpr>(CL->getInitializer()->IgnoreParens());
311
312  const ProgramState *state = Pred->getState();
313  SVal ILV = state->getSVal(ILE);
314  const LocationContext *LC = Pred->getLocationContext();
315  state = state->bindCompoundLiteral(CL, LC, ILV);
316
317  if (CL->isLValue())
318    B.generateNode(CL, Pred, state->BindExpr(CL, state->getLValue(CL, LC)));
319  else
320    B.generateNode(CL, Pred, state->BindExpr(CL, ILV));
321}
322
323void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
324                               ExplodedNodeSet &Dst) {
325
326  // FIXME: static variables may have an initializer, but the second
327  //  time a function is called those values may not be current.
328  //  This may need to be reflected in the CFG.
329
330  // Assumption: The CFG has one DeclStmt per Decl.
331  const Decl *D = *DS->decl_begin();
332
333  if (!D || !isa<VarDecl>(D)) {
334    //TODO:AZ: remove explicit insertion after refactoring is done.
335    Dst.insert(Pred);
336    return;
337  }
338
339  // FIXME: all pre/post visits should eventually be handled by ::Visit().
340  ExplodedNodeSet dstPreVisit;
341  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
342
343  StmtNodeBuilder B(dstPreVisit, Dst, *currentBuilderContext);
344  const VarDecl *VD = dyn_cast<VarDecl>(D);
345  for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
346       I!=E; ++I) {
347    ExplodedNode *N = *I;
348    const ProgramState *state = N->getState();
349
350    // Decls without InitExpr are not initialized explicitly.
351    const LocationContext *LC = N->getLocationContext();
352
353    if (const Expr *InitEx = VD->getInit()) {
354      SVal InitVal = state->getSVal(InitEx);
355
356      // We bound the temp obj region to the CXXConstructExpr. Now recover
357      // the lazy compound value when the variable is not a reference.
358      if (AMgr.getLangOptions().CPlusPlus && VD->getType()->isRecordType() &&
359          !VD->getType()->isReferenceType() && isa<loc::MemRegionVal>(InitVal)){
360        InitVal = state->getSVal(cast<loc::MemRegionVal>(InitVal).getRegion());
361        assert(isa<nonloc::LazyCompoundVal>(InitVal));
362      }
363
364      // Recover some path-sensitivity if a scalar value evaluated to
365      // UnknownVal.
366      if ((InitVal.isUnknown() ||
367           !getConstraintManager().canReasonAbout(InitVal)) &&
368          !VD->getType()->isReferenceType()) {
369        InitVal = svalBuilder.getConjuredSymbolVal(NULL, InitEx,
370                                 currentBuilderContext->getCurrentBlockCount());
371      }
372      B.takeNodes(N);
373      evalBind(Dst, DS, N, state->getLValue(VD, LC), InitVal, true);
374      B.addNodes(Dst);
375    }
376    else {
377      B.generateNode(DS, N,state->bindDeclWithNoInit(state->getRegion(VD, LC)));
378    }
379  }
380}
381
382void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
383                                  ExplodedNodeSet &Dst) {
384  assert(B->getOpcode() == BO_LAnd ||
385         B->getOpcode() == BO_LOr);
386
387  StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
388  const ProgramState *state = Pred->getState();
389  SVal X = state->getSVal(B);
390  assert(X.isUndef());
391
392  const Expr *Ex = (const Expr*) cast<UndefinedVal>(X).getData();
393  assert(Ex);
394
395  if (Ex == B->getRHS()) {
396    X = state->getSVal(Ex);
397
398    // Handle undefined values.
399    if (X.isUndef()) {
400      Bldr.generateNode(B, Pred, state->BindExpr(B, X));
401      return;
402    }
403
404    DefinedOrUnknownSVal XD = cast<DefinedOrUnknownSVal>(X);
405
406    // We took the RHS.  Because the value of the '&&' or '||' expression must
407    // evaluate to 0 or 1, we must assume the value of the RHS evaluates to 0
408    // or 1.  Alternatively, we could take a lazy approach, and calculate this
409    // value later when necessary.  We don't have the machinery in place for
410    // this right now, and since most logical expressions are used for branches,
411    // the payoff is not likely to be large.  Instead, we do eager evaluation.
412    if (const ProgramState *newState = state->assume(XD, true))
413      Bldr.generateNode(B, Pred,
414               newState->BindExpr(B, svalBuilder.makeIntVal(1U, B->getType())));
415
416    if (const ProgramState *newState = state->assume(XD, false))
417      Bldr.generateNode(B, Pred,
418               newState->BindExpr(B, svalBuilder.makeIntVal(0U, B->getType())));
419  }
420  else {
421    // We took the LHS expression.  Depending on whether we are '&&' or
422    // '||' we know what the value of the expression is via properties of
423    // the short-circuiting.
424    X = svalBuilder.makeIntVal(B->getOpcode() == BO_LAnd ? 0U : 1U,
425                               B->getType());
426    Bldr.generateNode(B, Pred, state->BindExpr(B, X));
427  }
428}
429
430void ExprEngine::VisitInitListExpr(const InitListExpr *IE,
431                                   ExplodedNode *Pred,
432                                   ExplodedNodeSet &Dst) {
433  StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
434
435  const ProgramState *state = Pred->getState();
436  QualType T = getContext().getCanonicalType(IE->getType());
437  unsigned NumInitElements = IE->getNumInits();
438
439  if (T->isArrayType() || T->isRecordType() || T->isVectorType()) {
440    llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
441
442    // Handle base case where the initializer has no elements.
443    // e.g: static int* myArray[] = {};
444    if (NumInitElements == 0) {
445      SVal V = svalBuilder.makeCompoundVal(T, vals);
446      B.generateNode(IE, Pred, state->BindExpr(IE, V));
447      return;
448    }
449
450    for (InitListExpr::const_reverse_iterator it = IE->rbegin(),
451         ei = IE->rend(); it != ei; ++it) {
452      vals = getBasicVals().consVals(state->getSVal(cast<Expr>(*it)), vals);
453    }
454
455    B.generateNode(IE, Pred,
456                   state->BindExpr(IE, svalBuilder.makeCompoundVal(T, vals)));
457    return;
458  }
459
460  if (Loc::isLocType(T) || T->isIntegerType()) {
461    assert(IE->getNumInits() == 1);
462    const Expr *initEx = IE->getInit(0);
463    B.generateNode(IE, Pred, state->BindExpr(IE, state->getSVal(initEx)));
464    return;
465  }
466
467  llvm_unreachable("unprocessed InitListExpr type");
468}
469
470void ExprEngine::VisitGuardedExpr(const Expr *Ex,
471                                  const Expr *L,
472                                  const Expr *R,
473                                  ExplodedNode *Pred,
474                                  ExplodedNodeSet &Dst) {
475  StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
476
477  const ProgramState *state = Pred->getState();
478  SVal X = state->getSVal(Ex);
479  assert (X.isUndef());
480  const Expr *SE = (Expr*) cast<UndefinedVal>(X).getData();
481  assert(SE);
482  X = state->getSVal(SE);
483
484  // Make sure that we invalidate the previous binding.
485  B.generateNode(Ex, Pred, state->BindExpr(Ex, X, true));
486}
487
488void ExprEngine::
489VisitOffsetOfExpr(const OffsetOfExpr *OOE,
490                  ExplodedNode *Pred, ExplodedNodeSet &Dst) {
491  StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
492  Expr::EvalResult Res;
493  if (OOE->Evaluate(Res, getContext()) && Res.Val.isInt()) {
494    const APSInt &IV = Res.Val.getInt();
495    assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
496    assert(OOE->getType()->isIntegerType());
497    assert(IV.isSigned() == OOE->getType()->isSignedIntegerOrEnumerationType());
498    SVal X = svalBuilder.makeIntVal(IV);
499    B.generateNode(OOE, Pred, Pred->getState()->BindExpr(OOE, X));
500  }
501  // FIXME: Handle the case where __builtin_offsetof is not a constant.
502}
503
504
505void ExprEngine::
506VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
507                              ExplodedNode *Pred,
508                              ExplodedNodeSet &Dst) {
509  StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
510
511  QualType T = Ex->getTypeOfArgument();
512
513  if (Ex->getKind() == UETT_SizeOf) {
514    if (!T->isIncompleteType() && !T->isConstantSizeType()) {
515      assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
516
517      // FIXME: Add support for VLA type arguments and VLA expressions.
518      // When that happens, we should probably refactor VLASizeChecker's code.
519      return;
520    }
521    else if (T->getAs<ObjCObjectType>()) {
522      // Some code tries to take the sizeof an ObjCObjectType, relying that
523      // the compiler has laid out its representation.  Just report Unknown
524      // for these.
525      return;
526    }
527  }
528
529  Expr::EvalResult Result;
530  Ex->Evaluate(Result, getContext());
531  CharUnits amt = CharUnits::fromQuantity(Result.Val.getInt().getZExtValue());
532
533  const ProgramState *state = Pred->getState();
534  state = state->BindExpr(Ex, svalBuilder.makeIntVal(amt.getQuantity(),
535                                                     Ex->getType()));
536  Bldr.generateNode(Ex, Pred, state);
537}
538
539void ExprEngine::VisitUnaryOperator(const UnaryOperator* U,
540                                    ExplodedNode *Pred,
541                                    ExplodedNodeSet &Dst) {
542  StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
543  bool IncDec = false;
544  switch (U->getOpcode()) {
545    default: {
546      Bldr.takeNodes(Pred);
547      IncDec = true;
548      ExplodedNodeSet Tmp;
549      VisitIncrementDecrementOperator(U, Pred, Tmp);
550      Bldr.addNodes(Tmp);
551    }
552      break;
553    case UO_Real: {
554      const Expr *Ex = U->getSubExpr()->IgnoreParens();
555      ExplodedNodeSet Tmp;
556      Visit(Ex, Pred, Tmp);
557
558      for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
559
560        // FIXME: We don't have complex SValues yet.
561        if (Ex->getType()->isAnyComplexType()) {
562          // Just report "Unknown."
563          continue;
564        }
565
566        // For all other types, UO_Real is an identity operation.
567        assert (U->getType() == Ex->getType());
568        const ProgramState *state = (*I)->getState();
569        Bldr.generateNode(U, *I, state->BindExpr(U, state->getSVal(Ex)));
570      }
571
572      break;
573    }
574
575    case UO_Imag: {
576
577      const Expr *Ex = U->getSubExpr()->IgnoreParens();
578      ExplodedNodeSet Tmp;
579      Visit(Ex, Pred, Tmp);
580
581      for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
582        // FIXME: We don't have complex SValues yet.
583        if (Ex->getType()->isAnyComplexType()) {
584          // Just report "Unknown."
585          continue;
586        }
587
588        // For all other types, UO_Imag returns 0.
589        const ProgramState *state = (*I)->getState();
590        SVal X = svalBuilder.makeZeroVal(Ex->getType());
591        Bldr.generateNode(U, *I, state->BindExpr(U, X));
592      }
593
594      break;
595    }
596
597    case UO_Plus:
598      assert(!U->isLValue());
599      // FALL-THROUGH.
600    case UO_Deref:
601    case UO_AddrOf:
602    case UO_Extension: {
603
604      // Unary "+" is a no-op, similar to a parentheses.  We still have places
605      // where it may be a block-level expression, so we need to
606      // generate an extra node that just propagates the value of the
607      // subexpression.
608
609      const Expr *Ex = U->getSubExpr()->IgnoreParens();
610      ExplodedNodeSet Tmp;
611      Visit(Ex, Pred, Tmp);
612
613      for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
614        const ProgramState *state = (*I)->getState();
615        Bldr.generateNode(U, *I, state->BindExpr(U, state->getSVal(Ex)));
616      }
617
618      break;
619    }
620
621    case UO_LNot:
622    case UO_Minus:
623    case UO_Not: {
624      assert (!U->isLValue());
625      const Expr *Ex = U->getSubExpr()->IgnoreParens();
626      ExplodedNodeSet Tmp;
627      Visit(Ex, Pred, Tmp);
628
629      for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
630        const ProgramState *state = (*I)->getState();
631
632        // Get the value of the subexpression.
633        SVal V = state->getSVal(Ex);
634
635        if (V.isUnknownOrUndef()) {
636          Bldr.generateNode(U, *I, state->BindExpr(U, V));
637          continue;
638        }
639
640        switch (U->getOpcode()) {
641          default:
642            llvm_unreachable("Invalid Opcode.");
643
644          case UO_Not:
645            // FIXME: Do we need to handle promotions?
646            state = state->BindExpr(U, evalComplement(cast<NonLoc>(V)));
647            break;
648
649          case UO_Minus:
650            // FIXME: Do we need to handle promotions?
651            state = state->BindExpr(U, evalMinus(cast<NonLoc>(V)));
652            break;
653
654          case UO_LNot:
655
656            // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
657            //
658            //  Note: technically we do "E == 0", but this is the same in the
659            //    transfer functions as "0 == E".
660            SVal Result;
661
662            if (isa<Loc>(V)) {
663              Loc X = svalBuilder.makeNull();
664              Result = evalBinOp(state, BO_EQ, cast<Loc>(V), X,
665                                 U->getType());
666            }
667            else {
668              nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
669              Result = evalBinOp(state, BO_EQ, cast<NonLoc>(V), X,
670                                 U->getType());
671            }
672
673            state = state->BindExpr(U, Result);
674
675            break;
676        }
677        Bldr.generateNode(U, *I, state);
678      }
679      break;
680    }
681  }
682
683}
684
685void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
686                                                 ExplodedNode *Pred,
687                                                 ExplodedNodeSet &Dst) {
688  // Handle ++ and -- (both pre- and post-increment).
689  assert (U->isIncrementDecrementOp());
690  ExplodedNodeSet Tmp;
691  const Expr *Ex = U->getSubExpr()->IgnoreParens();
692  Visit(Ex, Pred, Tmp);
693
694  for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I) {
695
696    const ProgramState *state = (*I)->getState();
697    SVal loc = state->getSVal(Ex);
698
699    // Perform a load.
700    ExplodedNodeSet Tmp2;
701    evalLoad(Tmp2, Ex, *I, state, loc);
702
703    ExplodedNodeSet Dst2;
704    StmtNodeBuilder Bldr(Tmp2, Dst2, *currentBuilderContext);
705    for (ExplodedNodeSet::iterator I2=Tmp2.begin(), E2=Tmp2.end();I2!=E2;++I2) {
706
707      state = (*I2)->getState();
708      SVal V2_untested = state->getSVal(Ex);
709
710      // Propagate unknown and undefined values.
711      if (V2_untested.isUnknownOrUndef()) {
712        Bldr.generateNode(U, *I2, state->BindExpr(U, V2_untested));
713        continue;
714      }
715      DefinedSVal V2 = cast<DefinedSVal>(V2_untested);
716
717      // Handle all other values.
718      BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add
719      : BO_Sub;
720
721      // If the UnaryOperator has non-location type, use its type to create the
722      // constant value. If the UnaryOperator has location type, create the
723      // constant with int type and pointer width.
724      SVal RHS;
725
726      if (U->getType()->isAnyPointerType())
727        RHS = svalBuilder.makeArrayIndex(1);
728      else
729        RHS = svalBuilder.makeIntVal(1, U->getType());
730
731      SVal Result = evalBinOp(state, Op, V2, RHS, U->getType());
732
733      // Conjure a new symbol if necessary to recover precision.
734      if (Result.isUnknown() || !getConstraintManager().canReasonAbout(Result)){
735        DefinedOrUnknownSVal SymVal =
736        svalBuilder.getConjuredSymbolVal(NULL, Ex,
737                                 currentBuilderContext->getCurrentBlockCount());
738        Result = SymVal;
739
740        // If the value is a location, ++/-- should always preserve
741        // non-nullness.  Check if the original value was non-null, and if so
742        // propagate that constraint.
743        if (Loc::isLocType(U->getType())) {
744          DefinedOrUnknownSVal Constraint =
745          svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
746
747          if (!state->assume(Constraint, true)) {
748            // It isn't feasible for the original value to be null.
749            // Propagate this constraint.
750            Constraint = svalBuilder.evalEQ(state, SymVal,
751                                         svalBuilder.makeZeroVal(U->getType()));
752
753
754            state = state->assume(Constraint, false);
755            assert(state);
756          }
757        }
758      }
759
760      // Since the lvalue-to-rvalue conversion is explicit in the AST,
761      // we bind an l-value if the operator is prefix and an lvalue (in C++).
762      if (U->isLValue())
763        state = state->BindExpr(U, loc);
764      else
765        state = state->BindExpr(U, U->isPostfix() ? V2 : Result);
766
767      // Perform the store.
768      Bldr.takeNodes(*I2);
769      ExplodedNodeSet Dst4;
770      evalStore(Dst4, NULL, U, *I2, state, loc, Result);
771      Bldr.addNodes(Dst4);
772    }
773    Dst.insert(Dst2);
774  }
775}
776