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