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