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     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->isGLValue() ? 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 
62       if (B->isAdditiveOp()) {
63         // If one of the operands is a location, conjure a symbol for the other
64         // one (offset) if it's unknown so that memory arithmetic always
65         // results in an ElementRegion.
66         // TODO: This can be removed after we enable history tracking with
67         // SymSymExpr.
68         unsigned Count = currentBuilderContext->getCurrentBlockCount();
69         if (isa<Loc>(LeftV) &&
70             RHS->getType()->isIntegerType() && RightV.isUnknown()) {
71           RightV = svalBuilder.getConjuredSymbolVal(RHS, LCtx,
72                                                     RHS->getType(), Count);
73         }
74         if (isa<Loc>(RightV) &&
75             LHS->getType()->isIntegerType() && LeftV.isUnknown()) {
76           LeftV = svalBuilder.getConjuredSymbolVal(LHS, LCtx,
77                                                    LHS->getType(), Count);
78         }
79       }
80 
81       // Process non-assignments except commas or short-circuited
82       // logical expressions (LAnd and LOr).
83       SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());
84       if (Result.isUnknown()) {
85         Bldr.generateNode(B, *it, state);
86         continue;
87       }
88 
89       state = state->BindExpr(B, LCtx, Result);
90       Bldr.generateNode(B, *it, state);
91       continue;
92     }
93 
94     assert (B->isCompoundAssignmentOp());
95 
96     switch (Op) {
97       default:
98         llvm_unreachable("Invalid opcode for compound assignment.");
99       case BO_MulAssign: Op = BO_Mul; break;
100       case BO_DivAssign: Op = BO_Div; break;
101       case BO_RemAssign: Op = BO_Rem; break;
102       case BO_AddAssign: Op = BO_Add; break;
103       case BO_SubAssign: Op = BO_Sub; break;
104       case BO_ShlAssign: Op = BO_Shl; break;
105       case BO_ShrAssign: Op = BO_Shr; break;
106       case BO_AndAssign: Op = BO_And; break;
107       case BO_XorAssign: Op = BO_Xor; break;
108       case BO_OrAssign:  Op = BO_Or;  break;
109     }
110 
111     // Perform a load (the LHS).  This performs the checks for
112     // null dereferences, and so on.
113     ExplodedNodeSet Tmp;
114     SVal location = LeftV;
115     evalLoad(Tmp, B, LHS, *it, state, location);
116 
117     for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E;
118          ++I) {
119 
120       state = (*I)->getState();
121       const LocationContext *LCtx = (*I)->getLocationContext();
122       SVal V = state->getSVal(LHS, LCtx);
123 
124       // Get the computation type.
125       QualType CTy =
126         cast<CompoundAssignOperator>(B)->getComputationResultType();
127       CTy = getContext().getCanonicalType(CTy);
128 
129       QualType CLHSTy =
130         cast<CompoundAssignOperator>(B)->getComputationLHSType();
131       CLHSTy = getContext().getCanonicalType(CLHSTy);
132 
133       QualType LTy = getContext().getCanonicalType(LHS->getType());
134 
135       // Promote LHS.
136       V = svalBuilder.evalCast(V, CLHSTy, LTy);
137 
138       // Compute the result of the operation.
139       SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
140                                          B->getType(), CTy);
141 
142       // EXPERIMENTAL: "Conjured" symbols.
143       // FIXME: Handle structs.
144 
145       SVal LHSVal;
146 
147       if (Result.isUnknown()) {
148 
149         unsigned Count = currentBuilderContext->getCurrentBlockCount();
150 
151         // The symbolic value is actually for the type of the left-hand side
152         // expression, not the computation type, as this is the value the
153         // LValue on the LHS will bind to.
154         LHSVal = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), LCtx,
155 						  LTy, Count);
156 
157         // However, we need to convert the symbol to the computation type.
158         Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
159       }
160       else {
161         // The left-hand side may bind to a different value then the
162         // computation type.
163         LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
164       }
165 
166       // In C++, assignment and compound assignment operators return an
167       // lvalue.
168       if (B->isGLValue())
169         state = state->BindExpr(B, LCtx, location);
170       else
171         state = state->BindExpr(B, LCtx, Result);
172 
173       evalStore(Tmp2, B, LHS, *I, state, location, LHSVal);
174     }
175   }
176 
177   // FIXME: postvisits eventually go in ::Visit()
178   getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this);
179 }
180 
181 void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
182                                 ExplodedNodeSet &Dst) {
183 
184   CanQualType T = getContext().getCanonicalType(BE->getType());
185 
186   // Get the value of the block itself.
187   SVal V = svalBuilder.getBlockPointer(BE->getBlockDecl(), T,
188                                        Pred->getLocationContext());
189 
190   ProgramStateRef State = Pred->getState();
191 
192   // If we created a new MemRegion for the block, we should explicitly bind
193   // the captured variables.
194   if (const BlockDataRegion *BDR =
195       dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
196 
197     BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
198                                               E = BDR->referenced_vars_end();
199 
200     for (; I != E; ++I) {
201       const MemRegion *capturedR = I.getCapturedRegion();
202       const MemRegion *originalR = I.getOriginalRegion();
203       if (capturedR != originalR) {
204         SVal originalV = State->getSVal(loc::MemRegionVal(originalR));
205         State = State->bindLoc(loc::MemRegionVal(capturedR), originalV);
206       }
207     }
208   }
209 
210   ExplodedNodeSet Tmp;
211   StmtNodeBuilder Bldr(Pred, Tmp, *currentBuilderContext);
212   Bldr.generateNode(BE, Pred,
213                     State->BindExpr(BE, Pred->getLocationContext(), V),
214                     false, 0,
215                     ProgramPoint::PostLValueKind);
216 
217   // FIXME: Move all post/pre visits to ::Visit().
218   getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
219 }
220 
221 void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
222                            ExplodedNode *Pred, ExplodedNodeSet &Dst) {
223 
224   ExplodedNodeSet dstPreStmt;
225   getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this);
226 
227   if (CastE->getCastKind() == CK_LValueToRValue) {
228     for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
229          I!=E; ++I) {
230       ExplodedNode *subExprNode = *I;
231       ProgramStateRef state = subExprNode->getState();
232       const LocationContext *LCtx = subExprNode->getLocationContext();
233       evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, LCtx));
234     }
235     return;
236   }
237 
238   // All other casts.
239   QualType T = CastE->getType();
240   QualType ExTy = Ex->getType();
241 
242   if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
243     T = ExCast->getTypeAsWritten();
244 
245   StmtNodeBuilder Bldr(dstPreStmt, Dst, *currentBuilderContext);
246   for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
247        I != E; ++I) {
248 
249     Pred = *I;
250 
251     switch (CastE->getCastKind()) {
252       case CK_LValueToRValue:
253         llvm_unreachable("LValueToRValue casts handled earlier.");
254       case CK_ToVoid:
255         continue;
256         // The analyzer doesn't do anything special with these casts,
257         // since it understands retain/release semantics already.
258       case CK_ARCProduceObject:
259       case CK_ARCConsumeObject:
260       case CK_ARCReclaimReturnedObject:
261       case CK_ARCExtendBlockObject: // Fall-through.
262       case CK_CopyAndAutoreleaseBlockObject:
263         // The analyser can ignore atomic casts for now, although some future
264         // checkers may want to make certain that you're not modifying the same
265         // value through atomic and nonatomic pointers.
266       case CK_AtomicToNonAtomic:
267       case CK_NonAtomicToAtomic:
268         // True no-ops.
269       case CK_NoOp:
270       case CK_FunctionToPointerDecay: {
271         // Copy the SVal of Ex to CastE.
272         ProgramStateRef state = Pred->getState();
273         const LocationContext *LCtx = Pred->getLocationContext();
274         SVal V = state->getSVal(Ex, LCtx);
275         state = state->BindExpr(CastE, LCtx, V);
276         Bldr.generateNode(CastE, Pred, state);
277         continue;
278       }
279       case CK_Dependent:
280       case CK_ArrayToPointerDecay:
281       case CK_BitCast:
282       case CK_IntegralCast:
283       case CK_NullToPointer:
284       case CK_IntegralToPointer:
285       case CK_PointerToIntegral:
286       case CK_PointerToBoolean:
287       case CK_IntegralToBoolean:
288       case CK_IntegralToFloating:
289       case CK_FloatingToIntegral:
290       case CK_FloatingToBoolean:
291       case CK_FloatingCast:
292       case CK_FloatingRealToComplex:
293       case CK_FloatingComplexToReal:
294       case CK_FloatingComplexToBoolean:
295       case CK_FloatingComplexCast:
296       case CK_FloatingComplexToIntegralComplex:
297       case CK_IntegralRealToComplex:
298       case CK_IntegralComplexToReal:
299       case CK_IntegralComplexToBoolean:
300       case CK_IntegralComplexCast:
301       case CK_IntegralComplexToFloatingComplex:
302       case CK_CPointerToObjCPointerCast:
303       case CK_BlockPointerToObjCPointerCast:
304       case CK_AnyPointerToBlockPointerCast:
305       case CK_ObjCObjectLValueCast: {
306         // Delegate to SValBuilder to process.
307         ProgramStateRef state = Pred->getState();
308         const LocationContext *LCtx = Pred->getLocationContext();
309         SVal V = state->getSVal(Ex, LCtx);
310         V = svalBuilder.evalCast(V, T, ExTy);
311         if (const MemRegion *R = V.getAsRegion()) {
312           state = state->addDynamicTypeInfo(R, T);
313         }
314         state = state->BindExpr(CastE, LCtx, V);
315         Bldr.generateNode(CastE, Pred, state);
316         continue;
317       }
318       case CK_DerivedToBase:
319       case CK_UncheckedDerivedToBase: {
320         // For DerivedToBase cast, delegate to the store manager.
321         ProgramStateRef state = Pred->getState();
322         const LocationContext *LCtx = Pred->getLocationContext();
323         SVal val = state->getSVal(Ex, LCtx);
324         val = getStoreManager().evalDerivedToBase(val, T);
325         state = state->BindExpr(CastE, LCtx, val);
326         Bldr.generateNode(CastE, Pred, state);
327         continue;
328       }
329       // Handle C++ dyn_cast.
330       case CK_Dynamic: {
331         ProgramStateRef state = Pred->getState();
332         const LocationContext *LCtx = Pred->getLocationContext();
333         SVal val = state->getSVal(Ex, LCtx);
334 
335         // Compute the type of the result.
336         QualType resultType = CastE->getType();
337         if (CastE->isGLValue())
338           resultType = getContext().getPointerType(resultType);
339 
340         bool Failed = false;
341 
342         // Check if the value being cast evaluates to 0.
343         if (val.isZeroConstant())
344           Failed = true;
345         // Else, evaluate the cast.
346         else
347           val = getStoreManager().evalDynamicCast(val, T, Failed);
348 
349         if (Failed) {
350           if (T->isReferenceType()) {
351             // A bad_cast exception is thrown if input value is a reference.
352             // Currently, we model this, by generating a sink.
353             Bldr.generateNode(CastE, Pred, state, true);
354             continue;
355           } else {
356             // If the cast fails on a pointer, bind to 0.
357             state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull());
358           }
359         } else {
360           // If we don't know if the cast succeeded, conjure a new symbol.
361           if (val.isUnknown()) {
362             DefinedOrUnknownSVal NewSym = svalBuilder.getConjuredSymbolVal(NULL,
363                                  CastE, LCtx, resultType,
364                                  currentBuilderContext->getCurrentBlockCount());
365             state = state->BindExpr(CastE, LCtx, NewSym);
366           } else
367             // Else, bind to the derived region value.
368             state = state->BindExpr(CastE, LCtx, val);
369         }
370         Bldr.generateNode(CastE, Pred, state);
371         continue;
372       }
373       // Various C++ casts that are not handled yet.
374       case CK_ToUnion:
375       case CK_BaseToDerived:
376       case CK_NullToMemberPointer:
377       case CK_BaseToDerivedMemberPointer:
378       case CK_DerivedToBaseMemberPointer:
379       case CK_ReinterpretMemberPointer:
380       case CK_UserDefinedConversion:
381       case CK_ConstructorConversion:
382       case CK_VectorSplat:
383       case CK_MemberPointerToBoolean:
384       case CK_LValueBitCast: {
385         // Recover some path-sensitivty by conjuring a new value.
386         QualType resultType = CastE->getType();
387         if (CastE->isGLValue())
388           resultType = getContext().getPointerType(resultType);
389         const LocationContext *LCtx = Pred->getLocationContext();
390         SVal result = svalBuilder.getConjuredSymbolVal(NULL, CastE, LCtx,
391                     resultType, currentBuilderContext->getCurrentBlockCount());
392         ProgramStateRef state = Pred->getState()->BindExpr(CastE, LCtx,
393                                                                result);
394         Bldr.generateNode(CastE, Pred, state);
395         continue;
396       }
397     }
398   }
399 }
400 
401 void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
402                                           ExplodedNode *Pred,
403                                           ExplodedNodeSet &Dst) {
404   StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
405 
406   const InitListExpr *ILE
407     = cast<InitListExpr>(CL->getInitializer()->IgnoreParens());
408 
409   ProgramStateRef state = Pred->getState();
410   SVal ILV = state->getSVal(ILE, Pred->getLocationContext());
411   const LocationContext *LC = Pred->getLocationContext();
412   state = state->bindCompoundLiteral(CL, LC, ILV);
413 
414   // Compound literal expressions are a GNU extension in C++.
415   // Unlike in C, where CLs are lvalues, in C++ CLs are prvalues,
416   // and like temporary objects created by the functional notation T()
417   // CLs are destroyed at the end of the containing full-expression.
418   // HOWEVER, an rvalue of array type is not something the analyzer can
419   // reason about, since we expect all regions to be wrapped in Locs.
420   // So we treat array CLs as lvalues as well, knowing that they will decay
421   // to pointers as soon as they are used.
422   if (CL->isGLValue() || CL->getType()->isArrayType())
423     B.generateNode(CL, Pred, state->BindExpr(CL, LC, state->getLValue(CL, LC)));
424   else
425     B.generateNode(CL, Pred, state->BindExpr(CL, LC, ILV));
426 }
427 
428 void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
429                                ExplodedNodeSet &Dst) {
430 
431   // FIXME: static variables may have an initializer, but the second
432   //  time a function is called those values may not be current.
433   //  This may need to be reflected in the CFG.
434 
435   // Assumption: The CFG has one DeclStmt per Decl.
436   const Decl *D = *DS->decl_begin();
437 
438   if (!D || !isa<VarDecl>(D)) {
439     //TODO:AZ: remove explicit insertion after refactoring is done.
440     Dst.insert(Pred);
441     return;
442   }
443 
444   // FIXME: all pre/post visits should eventually be handled by ::Visit().
445   ExplodedNodeSet dstPreVisit;
446   getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
447 
448   StmtNodeBuilder B(dstPreVisit, Dst, *currentBuilderContext);
449   const VarDecl *VD = dyn_cast<VarDecl>(D);
450   for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
451        I!=E; ++I) {
452     ExplodedNode *N = *I;
453     ProgramStateRef state = N->getState();
454 
455     // Decls without InitExpr are not initialized explicitly.
456     const LocationContext *LC = N->getLocationContext();
457 
458     if (const Expr *InitEx = VD->getInit()) {
459       SVal InitVal = state->getSVal(InitEx, LC);
460 
461       if (InitVal == state->getLValue(VD, LC) ||
462           (VD->getType()->isArrayType() &&
463            isa<CXXConstructExpr>(InitEx->IgnoreImplicit()))) {
464         // We constructed the object directly in the variable.
465         // No need to bind anything.
466         B.generateNode(DS, N, state);
467       } else {
468         // We bound the temp obj region to the CXXConstructExpr. Now recover
469         // the lazy compound value when the variable is not a reference.
470         if (AMgr.getLangOpts().CPlusPlus && VD->getType()->isRecordType() &&
471             !VD->getType()->isReferenceType() && isa<loc::MemRegionVal>(InitVal)){
472           InitVal = state->getSVal(cast<loc::MemRegionVal>(InitVal).getRegion());
473           assert(isa<nonloc::LazyCompoundVal>(InitVal));
474         }
475 
476         // Recover some path-sensitivity if a scalar value evaluated to
477         // UnknownVal.
478         if (InitVal.isUnknown()) {
479           QualType Ty = InitEx->getType();
480           if (InitEx->isGLValue()) {
481             Ty = getContext().getPointerType(Ty);
482           }
483 
484           InitVal = svalBuilder.getConjuredSymbolVal(NULL, InitEx, LC, Ty,
485                                    currentBuilderContext->getCurrentBlockCount());
486         }
487         B.takeNodes(N);
488         ExplodedNodeSet Dst2;
489         evalBind(Dst2, DS, N, state->getLValue(VD, LC), InitVal, true);
490         B.addNodes(Dst2);
491       }
492     }
493     else {
494       B.generateNode(DS, N,state->bindDeclWithNoInit(state->getRegion(VD, LC)));
495     }
496   }
497 }
498 
499 void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
500                                   ExplodedNodeSet &Dst) {
501   assert(B->getOpcode() == BO_LAnd ||
502          B->getOpcode() == BO_LOr);
503 
504   StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
505   ProgramStateRef state = Pred->getState();
506 
507   ExplodedNode *N = Pred;
508   while (!isa<BlockEntrance>(N->getLocation())) {
509     ProgramPoint P = N->getLocation();
510     assert(isa<PreStmt>(P)|| isa<PreStmtPurgeDeadSymbols>(P));
511     (void) P;
512     assert(N->pred_size() == 1);
513     N = *N->pred_begin();
514   }
515   assert(N->pred_size() == 1);
516   N = *N->pred_begin();
517   BlockEdge BE = cast<BlockEdge>(N->getLocation());
518   SVal X;
519 
520   // Determine the value of the expression by introspecting how we
521   // got this location in the CFG.  This requires looking at the previous
522   // block we were in and what kind of control-flow transfer was involved.
523   const CFGBlock *SrcBlock = BE.getSrc();
524   // The only terminator (if there is one) that makes sense is a logical op.
525   CFGTerminator T = SrcBlock->getTerminator();
526   if (const BinaryOperator *Term = cast_or_null<BinaryOperator>(T.getStmt())) {
527     (void) Term;
528     assert(Term->isLogicalOp());
529     assert(SrcBlock->succ_size() == 2);
530     // Did we take the true or false branch?
531     unsigned constant = (*SrcBlock->succ_begin() == BE.getDst()) ? 1 : 0;
532     X = svalBuilder.makeIntVal(constant, B->getType());
533   }
534   else {
535     // If there is no terminator, by construction the last statement
536     // in SrcBlock is the value of the enclosing expression.
537     assert(!SrcBlock->empty());
538     CFGStmt Elem = cast<CFGStmt>(*SrcBlock->rbegin());
539     const Stmt *S = Elem.getStmt();
540     X = N->getState()->getSVal(S, Pred->getLocationContext());
541   }
542 
543   Bldr.generateNode(B, Pred, state->BindExpr(B, Pred->getLocationContext(), X));
544 }
545 
546 void ExprEngine::VisitInitListExpr(const InitListExpr *IE,
547                                    ExplodedNode *Pred,
548                                    ExplodedNodeSet &Dst) {
549   StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
550 
551   ProgramStateRef state = Pred->getState();
552   const LocationContext *LCtx = Pred->getLocationContext();
553   QualType T = getContext().getCanonicalType(IE->getType());
554   unsigned NumInitElements = IE->getNumInits();
555 
556   if (T->isArrayType() || T->isRecordType() || T->isVectorType()) {
557     llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
558 
559     // Handle base case where the initializer has no elements.
560     // e.g: static int* myArray[] = {};
561     if (NumInitElements == 0) {
562       SVal V = svalBuilder.makeCompoundVal(T, vals);
563       B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
564       return;
565     }
566 
567     for (InitListExpr::const_reverse_iterator it = IE->rbegin(),
568          ei = IE->rend(); it != ei; ++it) {
569       vals = getBasicVals().consVals(state->getSVal(cast<Expr>(*it), LCtx),
570                                      vals);
571     }
572 
573     B.generateNode(IE, Pred,
574                    state->BindExpr(IE, LCtx,
575                                    svalBuilder.makeCompoundVal(T, vals)));
576     return;
577   }
578 
579   // Handle scalars: int{5} and int{}.
580   assert(NumInitElements <= 1);
581 
582   SVal V;
583   if (NumInitElements == 0)
584     V = getSValBuilder().makeZeroVal(T);
585   else
586     V = state->getSVal(IE->getInit(0), LCtx);
587 
588   B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
589 }
590 
591 void ExprEngine::VisitGuardedExpr(const Expr *Ex,
592                                   const Expr *L,
593                                   const Expr *R,
594                                   ExplodedNode *Pred,
595                                   ExplodedNodeSet &Dst) {
596   StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
597   ProgramStateRef state = Pred->getState();
598   const LocationContext *LCtx = Pred->getLocationContext();
599   const CFGBlock *SrcBlock = 0;
600 
601   for (const ExplodedNode *N = Pred ; N ; N = *N->pred_begin()) {
602     ProgramPoint PP = N->getLocation();
603     if (isa<PreStmtPurgeDeadSymbols>(PP) || isa<BlockEntrance>(PP)) {
604       assert(N->pred_size() == 1);
605       continue;
606     }
607     SrcBlock = cast<BlockEdge>(&PP)->getSrc();
608     break;
609   }
610 
611   // Find the last expression in the predecessor block.  That is the
612   // expression that is used for the value of the ternary expression.
613   bool hasValue = false;
614   SVal V;
615 
616   for (CFGBlock::const_reverse_iterator I = SrcBlock->rbegin(),
617                                         E = SrcBlock->rend(); I != E; ++I) {
618     CFGElement CE = *I;
619     if (CFGStmt *CS = dyn_cast<CFGStmt>(&CE)) {
620       const Expr *ValEx = cast<Expr>(CS->getStmt());
621       hasValue = true;
622       V = state->getSVal(ValEx, LCtx);
623       break;
624     }
625   }
626 
627   assert(hasValue);
628   (void) hasValue;
629 
630   // Generate a new node with the binding from the appropriate path.
631   B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true));
632 }
633 
634 void ExprEngine::
635 VisitOffsetOfExpr(const OffsetOfExpr *OOE,
636                   ExplodedNode *Pred, ExplodedNodeSet &Dst) {
637   StmtNodeBuilder B(Pred, Dst, *currentBuilderContext);
638   APSInt IV;
639   if (OOE->EvaluateAsInt(IV, getContext())) {
640     assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
641     assert(OOE->getType()->isIntegerType());
642     assert(IV.isSigned() == OOE->getType()->isSignedIntegerOrEnumerationType());
643     SVal X = svalBuilder.makeIntVal(IV);
644     B.generateNode(OOE, Pred,
645                    Pred->getState()->BindExpr(OOE, Pred->getLocationContext(),
646                                               X));
647   }
648   // FIXME: Handle the case where __builtin_offsetof is not a constant.
649 }
650 
651 
652 void ExprEngine::
653 VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
654                               ExplodedNode *Pred,
655                               ExplodedNodeSet &Dst) {
656   StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
657 
658   QualType T = Ex->getTypeOfArgument();
659 
660   if (Ex->getKind() == UETT_SizeOf) {
661     if (!T->isIncompleteType() && !T->isConstantSizeType()) {
662       assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
663 
664       // FIXME: Add support for VLA type arguments and VLA expressions.
665       // When that happens, we should probably refactor VLASizeChecker's code.
666       return;
667     }
668     else if (T->getAs<ObjCObjectType>()) {
669       // Some code tries to take the sizeof an ObjCObjectType, relying that
670       // the compiler has laid out its representation.  Just report Unknown
671       // for these.
672       return;
673     }
674   }
675 
676   APSInt Value = Ex->EvaluateKnownConstInt(getContext());
677   CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
678 
679   ProgramStateRef state = Pred->getState();
680   state = state->BindExpr(Ex, Pred->getLocationContext(),
681                           svalBuilder.makeIntVal(amt.getQuantity(),
682                                                      Ex->getType()));
683   Bldr.generateNode(Ex, Pred, state);
684 }
685 
686 void ExprEngine::VisitUnaryOperator(const UnaryOperator* U,
687                                     ExplodedNode *Pred,
688                                     ExplodedNodeSet &Dst) {
689   StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
690   switch (U->getOpcode()) {
691     default: {
692       Bldr.takeNodes(Pred);
693       ExplodedNodeSet Tmp;
694       VisitIncrementDecrementOperator(U, Pred, Tmp);
695       Bldr.addNodes(Tmp);
696     }
697       break;
698     case UO_Real: {
699       const Expr *Ex = U->getSubExpr()->IgnoreParens();
700 
701       // FIXME: We don't have complex SValues yet.
702       if (Ex->getType()->isAnyComplexType()) {
703         // Just report "Unknown."
704         break;
705       }
706 
707       // For all other types, UO_Real is an identity operation.
708       assert (U->getType() == Ex->getType());
709       ProgramStateRef state = Pred->getState();
710       const LocationContext *LCtx = Pred->getLocationContext();
711       Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx,
712                                                  state->getSVal(Ex, LCtx)));
713       break;
714     }
715 
716     case UO_Imag: {
717       const Expr *Ex = U->getSubExpr()->IgnoreParens();
718       // FIXME: We don't have complex SValues yet.
719       if (Ex->getType()->isAnyComplexType()) {
720         // Just report "Unknown."
721         break;
722       }
723       // For all other types, UO_Imag returns 0.
724       ProgramStateRef state = Pred->getState();
725       const LocationContext *LCtx = Pred->getLocationContext();
726       SVal X = svalBuilder.makeZeroVal(Ex->getType());
727       Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, X));
728       break;
729     }
730 
731     case UO_Plus:
732       assert(!U->isGLValue());
733       // FALL-THROUGH.
734     case UO_Deref:
735     case UO_AddrOf:
736     case UO_Extension: {
737       // FIXME: We can probably just have some magic in Environment::getSVal()
738       // that propagates values, instead of creating a new node here.
739       //
740       // Unary "+" is a no-op, similar to a parentheses.  We still have places
741       // where it may be a block-level expression, so we need to
742       // generate an extra node that just propagates the value of the
743       // subexpression.
744       const Expr *Ex = U->getSubExpr()->IgnoreParens();
745       ProgramStateRef state = Pred->getState();
746       const LocationContext *LCtx = Pred->getLocationContext();
747       Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx,
748                                                  state->getSVal(Ex, LCtx)));
749       break;
750     }
751 
752     case UO_LNot:
753     case UO_Minus:
754     case UO_Not: {
755       assert (!U->isGLValue());
756       const Expr *Ex = U->getSubExpr()->IgnoreParens();
757       ProgramStateRef state = Pred->getState();
758       const LocationContext *LCtx = Pred->getLocationContext();
759 
760       // Get the value of the subexpression.
761       SVal V = state->getSVal(Ex, LCtx);
762 
763       if (V.isUnknownOrUndef()) {
764         Bldr.generateNode(U, Pred, state->BindExpr(U, LCtx, V));
765         break;
766       }
767 
768       switch (U->getOpcode()) {
769         default:
770           llvm_unreachable("Invalid Opcode.");
771         case UO_Not:
772           // FIXME: Do we need to handle promotions?
773           state = state->BindExpr(U, LCtx, evalComplement(cast<NonLoc>(V)));
774           break;
775         case UO_Minus:
776           // FIXME: Do we need to handle promotions?
777           state = state->BindExpr(U, LCtx, evalMinus(cast<NonLoc>(V)));
778           break;
779         case UO_LNot:
780           // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
781           //
782           //  Note: technically we do "E == 0", but this is the same in the
783           //    transfer functions as "0 == E".
784           SVal Result;
785           if (isa<Loc>(V)) {
786             Loc X = svalBuilder.makeNull();
787             Result = evalBinOp(state, BO_EQ, cast<Loc>(V), X,
788                                U->getType());
789           }
790           else {
791             nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
792             Result = evalBinOp(state, BO_EQ, cast<NonLoc>(V), X,
793                                U->getType());
794           }
795 
796           state = state->BindExpr(U, LCtx, Result);
797           break;
798       }
799       Bldr.generateNode(U, Pred, state);
800       break;
801     }
802   }
803 
804 }
805 
806 void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
807                                                  ExplodedNode *Pred,
808                                                  ExplodedNodeSet &Dst) {
809   // Handle ++ and -- (both pre- and post-increment).
810   assert (U->isIncrementDecrementOp());
811   const Expr *Ex = U->getSubExpr()->IgnoreParens();
812 
813   const LocationContext *LCtx = Pred->getLocationContext();
814   ProgramStateRef state = Pred->getState();
815   SVal loc = state->getSVal(Ex, LCtx);
816 
817   // Perform a load.
818   ExplodedNodeSet Tmp;
819   evalLoad(Tmp, U, Ex, Pred, state, loc);
820 
821   ExplodedNodeSet Dst2;
822   StmtNodeBuilder Bldr(Tmp, Dst2, *currentBuilderContext);
823   for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) {
824 
825     state = (*I)->getState();
826     assert(LCtx == (*I)->getLocationContext());
827     SVal V2_untested = state->getSVal(Ex, LCtx);
828 
829     // Propagate unknown and undefined values.
830     if (V2_untested.isUnknownOrUndef()) {
831       Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V2_untested));
832       continue;
833     }
834     DefinedSVal V2 = cast<DefinedSVal>(V2_untested);
835 
836     // Handle all other values.
837     BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub;
838 
839     // If the UnaryOperator has non-location type, use its type to create the
840     // constant value. If the UnaryOperator has location type, create the
841     // constant with int type and pointer width.
842     SVal RHS;
843 
844     if (U->getType()->isAnyPointerType())
845       RHS = svalBuilder.makeArrayIndex(1);
846     else
847       RHS = svalBuilder.makeIntVal(1, U->getType());
848 
849     SVal Result = evalBinOp(state, Op, V2, RHS, U->getType());
850 
851     // Conjure a new symbol if necessary to recover precision.
852     if (Result.isUnknown()){
853       DefinedOrUnknownSVal SymVal =
854 	svalBuilder.getConjuredSymbolVal(NULL, Ex, LCtx,
855                                currentBuilderContext->getCurrentBlockCount());
856       Result = SymVal;
857 
858       // If the value is a location, ++/-- should always preserve
859       // non-nullness.  Check if the original value was non-null, and if so
860       // propagate that constraint.
861       if (Loc::isLocType(U->getType())) {
862         DefinedOrUnknownSVal Constraint =
863         svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
864 
865         if (!state->assume(Constraint, true)) {
866           // It isn't feasible for the original value to be null.
867           // Propagate this constraint.
868           Constraint = svalBuilder.evalEQ(state, SymVal,
869                                        svalBuilder.makeZeroVal(U->getType()));
870 
871 
872           state = state->assume(Constraint, false);
873           assert(state);
874         }
875       }
876     }
877 
878     // Since the lvalue-to-rvalue conversion is explicit in the AST,
879     // we bind an l-value if the operator is prefix and an lvalue (in C++).
880     if (U->isGLValue())
881       state = state->BindExpr(U, LCtx, loc);
882     else
883       state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result);
884 
885     // Perform the store.
886     Bldr.takeNodes(*I);
887     ExplodedNodeSet Dst3;
888     evalStore(Dst3, U, U, *I, state, loc, Result);
889     Bldr.addNodes(Dst3);
890   }
891   Dst.insert(Dst2);
892 }
893