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