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