1 //=-- ExprEngineC.cpp - ExprEngine support for C expressions ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines ExprEngine's support for C expressions.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ExprCXX.h"
15 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
16 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
18 using namespace clang;
22 void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
24 ExplodedNodeSet &Dst) {
26 Expr *LHS = B->getLHS()->IgnoreParens();
27 Expr *RHS = B->getRHS()->IgnoreParens();
29 // FIXME: Prechecks eventually go in ::Visit().
30 ExplodedNodeSet CheckedSet;
32 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, B, *this);
34 // With both the LHS and RHS evaluated, process the operation itself.
35 for (ExplodedNodeSet::iterator it=CheckedSet.begin(), ei=CheckedSet.end();
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);
43 BinaryOperator::Opcode Op = B->getOpcode();
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);
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),
60 if (!B->isAssignmentOp()) {
61 StmtNodeBuilder Bldr(*it, Tmp2, *currBldrCtx);
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
69 unsigned Count = currBldrCtx->blockCount();
70 if (LeftV.getAs<Loc>() &&
71 RHS->getType()->isIntegralOrEnumerationType() &&
73 RightV = svalBuilder.conjureSymbolVal(RHS, LCtx, RHS->getType(),
76 if (RightV.getAs<Loc>() &&
77 LHS->getType()->isIntegralOrEnumerationType() &&
79 LeftV = svalBuilder.conjureSymbolVal(LHS, LCtx, LHS->getType(),
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);
92 state = state->BindExpr(B, LCtx, Result);
93 Bldr.generateNode(B, *it, state);
97 assert (B->isCompoundAssignmentOp());
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;
114 // Perform a load (the LHS). This performs the checks for
115 // null dereferences, and so on.
117 SVal location = LeftV;
118 evalLoad(Tmp, B, LHS, *it, state, location);
120 for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E;
123 state = (*I)->getState();
124 const LocationContext *LCtx = (*I)->getLocationContext();
125 SVal V = state->getSVal(LHS, LCtx);
127 // Get the computation type.
129 cast<CompoundAssignOperator>(B)->getComputationResultType();
130 CTy = getContext().getCanonicalType(CTy);
133 cast<CompoundAssignOperator>(B)->getComputationLHSType();
134 CLHSTy = getContext().getCanonicalType(CLHSTy);
136 QualType LTy = getContext().getCanonicalType(LHS->getType());
139 V = svalBuilder.evalCast(V, CLHSTy, LTy);
141 // Compute the result of the operation.
142 SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
145 // EXPERIMENTAL: "Conjured" symbols.
146 // FIXME: Handle structs.
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);
160 // The left-hand side may bind to a different value then the
162 LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
165 // In C++, assignment and compound assignment operators return an
168 state = state->BindExpr(B, LCtx, location);
170 state = state->BindExpr(B, LCtx, Result);
172 evalStore(Tmp2, B, LHS, *I, state, location, LHSVal);
176 // FIXME: postvisits eventually go in ::Visit()
177 getCheckerManager().runCheckersForPostStmt(Dst, Tmp2, B, *this);
180 void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
181 ExplodedNodeSet &Dst) {
183 CanQualType T = getContext().getCanonicalType(BE->getType());
185 // Get the value of the block itself.
186 SVal V = svalBuilder.getBlockPointer(BE->getBlockDecl(), T,
187 Pred->getLocationContext(),
188 currBldrCtx->blockCount());
190 ProgramStateRef State = Pred->getState();
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())) {
197 BlockDataRegion::referenced_vars_iterator I = BDR->referenced_vars_begin(),
198 E = BDR->referenced_vars_end();
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);
211 StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
212 Bldr.generateNode(BE, Pred,
213 State->BindExpr(BE, Pred->getLocationContext(), V),
214 0, ProgramPoint::PostLValueKind);
216 // FIXME: Move all post/pre visits to ::Visit().
217 getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
220 void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
221 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
223 ExplodedNodeSet dstPreStmt;
224 getCheckerManager().runCheckersForPreStmt(dstPreStmt, Pred, CastE, *this);
226 if (CastE->getCastKind() == CK_LValueToRValue) {
227 for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
229 ExplodedNode *subExprNode = *I;
230 ProgramStateRef state = subExprNode->getState();
231 const LocationContext *LCtx = subExprNode->getLocationContext();
232 evalLoad(Dst, CastE, CastE, subExprNode, state, state->getSVal(Ex, LCtx));
238 QualType T = CastE->getType();
239 QualType ExTy = Ex->getType();
241 if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
242 T = ExCast->getTypeAsWritten();
244 StmtNodeBuilder Bldr(dstPreStmt, Dst, *currBldrCtx);
245 for (ExplodedNodeSet::iterator I = dstPreStmt.begin(), E = dstPreStmt.end();
249 ProgramStateRef state = Pred->getState();
250 const LocationContext *LCtx = Pred->getLocationContext();
252 switch (CastE->getCastKind()) {
253 case CK_LValueToRValue:
254 llvm_unreachable("LValueToRValue casts handled earlier.");
257 // The analyzer doesn't do anything special with these casts,
258 // since it understands retain/release semantics already.
259 case CK_ARCProduceObject:
260 case CK_ARCConsumeObject:
261 case CK_ARCReclaimReturnedObject:
262 case CK_ARCExtendBlockObject: // Fall-through.
263 case CK_CopyAndAutoreleaseBlockObject:
264 // The analyser can ignore atomic casts for now, although some future
265 // checkers may want to make certain that you're not modifying the same
266 // value through atomic and nonatomic pointers.
267 case CK_AtomicToNonAtomic:
268 case CK_NonAtomicToAtomic:
271 case CK_ConstructorConversion:
272 case CK_UserDefinedConversion:
273 case CK_FunctionToPointerDecay:
274 case CK_BuiltinFnToFnPtr: {
275 // Copy the SVal of Ex to CastE.
276 ProgramStateRef state = Pred->getState();
277 const LocationContext *LCtx = Pred->getLocationContext();
278 SVal V = state->getSVal(Ex, LCtx);
279 state = state->BindExpr(CastE, LCtx, V);
280 Bldr.generateNode(CastE, Pred, state);
283 case CK_MemberPointerToBoolean:
284 // FIXME: For now, member pointers are represented by void *.
287 case CK_ArrayToPointerDecay:
289 case CK_IntegralCast:
290 case CK_NullToPointer:
291 case CK_IntegralToPointer:
292 case CK_PointerToIntegral:
293 case CK_PointerToBoolean:
294 case CK_IntegralToBoolean:
295 case CK_IntegralToFloating:
296 case CK_FloatingToIntegral:
297 case CK_FloatingToBoolean:
298 case CK_FloatingCast:
299 case CK_FloatingRealToComplex:
300 case CK_FloatingComplexToReal:
301 case CK_FloatingComplexToBoolean:
302 case CK_FloatingComplexCast:
303 case CK_FloatingComplexToIntegralComplex:
304 case CK_IntegralRealToComplex:
305 case CK_IntegralComplexToReal:
306 case CK_IntegralComplexToBoolean:
307 case CK_IntegralComplexCast:
308 case CK_IntegralComplexToFloatingComplex:
309 case CK_CPointerToObjCPointerCast:
310 case CK_BlockPointerToObjCPointerCast:
311 case CK_AnyPointerToBlockPointerCast:
312 case CK_ObjCObjectLValueCast:
313 case CK_ZeroToOCLEvent:
314 case CK_LValueBitCast: {
315 // Delegate to SValBuilder to process.
316 SVal V = state->getSVal(Ex, LCtx);
317 V = svalBuilder.evalCast(V, T, ExTy);
318 state = state->BindExpr(CastE, LCtx, V);
319 Bldr.generateNode(CastE, Pred, state);
322 case CK_DerivedToBase:
323 case CK_UncheckedDerivedToBase: {
324 // For DerivedToBase cast, delegate to the store manager.
325 SVal val = state->getSVal(Ex, LCtx);
326 val = getStoreManager().evalDerivedToBase(val, CastE);
327 state = state->BindExpr(CastE, LCtx, val);
328 Bldr.generateNode(CastE, Pred, state);
331 // Handle C++ dyn_cast.
333 SVal val = state->getSVal(Ex, LCtx);
335 // Compute the type of the result.
336 QualType resultType = CastE->getType();
337 if (CastE->isGLValue())
338 resultType = getContext().getPointerType(resultType);
342 // Check if the value being cast evaluates to 0.
343 if (val.isZeroConstant())
345 // Else, evaluate the cast.
347 val = getStoreManager().evalDynamicCast(val, T, 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.generateSink(CastE, Pred, state);
356 // If the cast fails on a pointer, bind to 0.
357 state = state->BindExpr(CastE, LCtx, svalBuilder.makeNull());
360 // If we don't know if the cast succeeded, conjure a new symbol.
361 if (val.isUnknown()) {
362 DefinedOrUnknownSVal NewSym =
363 svalBuilder.conjureSymbolVal(0, CastE, LCtx, resultType,
364 currBldrCtx->blockCount());
365 state = state->BindExpr(CastE, LCtx, NewSym);
367 // Else, bind to the derived region value.
368 state = state->BindExpr(CastE, LCtx, val);
370 Bldr.generateNode(CastE, Pred, state);
373 case CK_NullToMemberPointer: {
374 // FIXME: For now, member pointers are represented by void *.
375 SVal V = svalBuilder.makeNull();
376 state = state->BindExpr(CastE, LCtx, V);
377 Bldr.generateNode(CastE, Pred, state);
380 // Various C++ casts that are not handled yet.
382 case CK_BaseToDerived:
383 case CK_BaseToDerivedMemberPointer:
384 case CK_DerivedToBaseMemberPointer:
385 case CK_ReinterpretMemberPointer:
386 case CK_VectorSplat: {
387 // Recover some path-sensitivty by conjuring a new value.
388 QualType resultType = CastE->getType();
389 if (CastE->isGLValue())
390 resultType = getContext().getPointerType(resultType);
391 SVal result = svalBuilder.conjureSymbolVal(0, CastE, LCtx,
393 currBldrCtx->blockCount());
394 state = state->BindExpr(CastE, LCtx, result);
395 Bldr.generateNode(CastE, Pred, state);
402 void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr *CL,
404 ExplodedNodeSet &Dst) {
405 StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
407 ProgramStateRef State = Pred->getState();
408 const LocationContext *LCtx = Pred->getLocationContext();
410 const Expr *Init = CL->getInitializer();
411 SVal V = State->getSVal(CL->getInitializer(), LCtx);
413 if (isa<CXXConstructExpr>(Init)) {
414 // No work needed. Just pass the value up to this expression.
416 assert(isa<InitListExpr>(Init));
417 Loc CLLoc = State->getLValue(CL, LCtx);
418 State = State->bindLoc(CLLoc, V);
420 // Compound literal expressions are a GNU extension in C++.
421 // Unlike in C, where CLs are lvalues, in C++ CLs are prvalues,
422 // and like temporary objects created by the functional notation T()
423 // CLs are destroyed at the end of the containing full-expression.
424 // HOWEVER, an rvalue of array type is not something the analyzer can
425 // reason about, since we expect all regions to be wrapped in Locs.
426 // So we treat array CLs as lvalues as well, knowing that they will decay
427 // to pointers as soon as they are used.
428 if (CL->isGLValue() || CL->getType()->isArrayType())
432 B.generateNode(CL, Pred, State->BindExpr(CL, LCtx, V));
435 void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
436 ExplodedNodeSet &Dst) {
437 // Assumption: The CFG has one DeclStmt per Decl.
438 const VarDecl *VD = dyn_cast_or_null<VarDecl>(*DS->decl_begin());
441 //TODO:AZ: remove explicit insertion after refactoring is done.
446 // FIXME: all pre/post visits should eventually be handled by ::Visit().
447 ExplodedNodeSet dstPreVisit;
448 getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, DS, *this);
450 ExplodedNodeSet dstEvaluated;
451 StmtNodeBuilder B(dstPreVisit, dstEvaluated, *currBldrCtx);
452 for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end();
454 ExplodedNode *N = *I;
455 ProgramStateRef state = N->getState();
456 const LocationContext *LC = N->getLocationContext();
458 // Decls without InitExpr are not initialized explicitly.
459 if (const Expr *InitEx = VD->getInit()) {
461 // Note in the state that the initialization has occurred.
462 ExplodedNode *UpdatedN = N;
463 SVal InitVal = state->getSVal(InitEx, LC);
465 if (isa<CXXConstructExpr>(InitEx->IgnoreImplicit())) {
466 // We constructed the object directly in the variable.
467 // No need to bind anything.
468 B.generateNode(DS, UpdatedN, state);
470 // We bound the temp obj region to the CXXConstructExpr. Now recover
471 // the lazy compound value when the variable is not a reference.
472 if (AMgr.getLangOpts().CPlusPlus && VD->getType()->isRecordType() &&
473 !VD->getType()->isReferenceType()) {
474 if (Optional<loc::MemRegionVal> M =
475 InitVal.getAs<loc::MemRegionVal>()) {
476 InitVal = state->getSVal(M->getRegion());
477 assert(InitVal.getAs<nonloc::LazyCompoundVal>());
481 // Recover some path-sensitivity if a scalar value evaluated to
483 if (InitVal.isUnknown()) {
484 QualType Ty = InitEx->getType();
485 if (InitEx->isGLValue()) {
486 Ty = getContext().getPointerType(Ty);
489 InitVal = svalBuilder.conjureSymbolVal(0, InitEx, LC, Ty,
490 currBldrCtx->blockCount());
494 B.takeNodes(UpdatedN);
495 ExplodedNodeSet Dst2;
496 evalBind(Dst2, DS, UpdatedN, state->getLValue(VD, LC), InitVal, true);
501 B.generateNode(DS, N, state);
505 getCheckerManager().runCheckersForPostStmt(Dst, B.getResults(), DS, *this);
508 void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
509 ExplodedNodeSet &Dst) {
510 assert(B->getOpcode() == BO_LAnd ||
511 B->getOpcode() == BO_LOr);
513 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
514 ProgramStateRef state = Pred->getState();
516 ExplodedNode *N = Pred;
517 while (!N->getLocation().getAs<BlockEntrance>()) {
518 ProgramPoint P = N->getLocation();
519 assert(P.getAs<PreStmt>()|| P.getAs<PreStmtPurgeDeadSymbols>());
521 assert(N->pred_size() == 1);
522 N = *N->pred_begin();
524 assert(N->pred_size() == 1);
525 N = *N->pred_begin();
526 BlockEdge BE = N->getLocation().castAs<BlockEdge>();
529 // Determine the value of the expression by introspecting how we
530 // got this location in the CFG. This requires looking at the previous
531 // block we were in and what kind of control-flow transfer was involved.
532 const CFGBlock *SrcBlock = BE.getSrc();
533 // The only terminator (if there is one) that makes sense is a logical op.
534 CFGTerminator T = SrcBlock->getTerminator();
535 if (const BinaryOperator *Term = cast_or_null<BinaryOperator>(T.getStmt())) {
537 assert(Term->isLogicalOp());
538 assert(SrcBlock->succ_size() == 2);
539 // Did we take the true or false branch?
540 unsigned constant = (*SrcBlock->succ_begin() == BE.getDst()) ? 1 : 0;
541 X = svalBuilder.makeIntVal(constant, B->getType());
544 // If there is no terminator, by construction the last statement
545 // in SrcBlock is the value of the enclosing expression.
546 // However, we still need to constrain that value to be 0 or 1.
547 assert(!SrcBlock->empty());
548 CFGStmt Elem = SrcBlock->rbegin()->castAs<CFGStmt>();
549 const Expr *RHS = cast<Expr>(Elem.getStmt());
550 SVal RHSVal = N->getState()->getSVal(RHS, Pred->getLocationContext());
552 if (RHSVal.isUndef()) {
555 DefinedOrUnknownSVal DefinedRHS = RHSVal.castAs<DefinedOrUnknownSVal>();
556 ProgramStateRef StTrue, StFalse;
557 llvm::tie(StTrue, StFalse) = N->getState()->assume(DefinedRHS);
560 // We can't constrain the value to 0 or 1.
561 // The best we can do is a cast.
562 X = getSValBuilder().evalCast(RHSVal, B->getType(), RHS->getType());
564 // The value is known to be true.
565 X = getSValBuilder().makeIntVal(1, B->getType());
568 // The value is known to be false.
569 assert(StFalse && "Infeasible path!");
570 X = getSValBuilder().makeIntVal(0, B->getType());
574 Bldr.generateNode(B, Pred, state->BindExpr(B, Pred->getLocationContext(), X));
577 void ExprEngine::VisitInitListExpr(const InitListExpr *IE,
579 ExplodedNodeSet &Dst) {
580 StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
582 ProgramStateRef state = Pred->getState();
583 const LocationContext *LCtx = Pred->getLocationContext();
584 QualType T = getContext().getCanonicalType(IE->getType());
585 unsigned NumInitElements = IE->getNumInits();
587 if (!IE->isGLValue() &&
588 (T->isArrayType() || T->isRecordType() || T->isVectorType() ||
589 T->isAnyComplexType())) {
590 llvm::ImmutableList<SVal> vals = getBasicVals().getEmptySValList();
592 // Handle base case where the initializer has no elements.
593 // e.g: static int* myArray[] = {};
594 if (NumInitElements == 0) {
595 SVal V = svalBuilder.makeCompoundVal(T, vals);
596 B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
600 for (InitListExpr::const_reverse_iterator it = IE->rbegin(),
601 ei = IE->rend(); it != ei; ++it) {
602 SVal V = state->getSVal(cast<Expr>(*it), LCtx);
603 vals = getBasicVals().consVals(V, vals);
606 B.generateNode(IE, Pred,
607 state->BindExpr(IE, LCtx,
608 svalBuilder.makeCompoundVal(T, vals)));
612 // Handle scalars: int{5} and int{} and GLvalues.
613 // Note, if the InitListExpr is a GLvalue, it means that there is an address
614 // representing it, so it must have a single init element.
615 assert(NumInitElements <= 1);
618 if (NumInitElements == 0)
619 V = getSValBuilder().makeZeroVal(T);
621 V = state->getSVal(IE->getInit(0), LCtx);
623 B.generateNode(IE, Pred, state->BindExpr(IE, LCtx, V));
626 void ExprEngine::VisitGuardedExpr(const Expr *Ex,
630 ExplodedNodeSet &Dst) {
633 StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
634 ProgramStateRef state = Pred->getState();
635 const LocationContext *LCtx = Pred->getLocationContext();
636 const CFGBlock *SrcBlock = 0;
638 // Find the predecessor block.
639 ProgramStateRef SrcState = state;
640 for (const ExplodedNode *N = Pred ; N ; N = *N->pred_begin()) {
641 ProgramPoint PP = N->getLocation();
642 if (PP.getAs<PreStmtPurgeDeadSymbols>() || PP.getAs<BlockEntrance>()) {
643 assert(N->pred_size() == 1);
646 SrcBlock = PP.castAs<BlockEdge>().getSrc();
647 SrcState = N->getState();
651 assert(SrcBlock && "missing function entry");
653 // Find the last expression in the predecessor block. That is the
654 // expression that is used for the value of the ternary expression.
655 bool hasValue = false;
658 for (CFGBlock::const_reverse_iterator I = SrcBlock->rbegin(),
659 E = SrcBlock->rend(); I != E; ++I) {
661 if (Optional<CFGStmt> CS = CE.getAs<CFGStmt>()) {
662 const Expr *ValEx = cast<Expr>(CS->getStmt());
663 ValEx = ValEx->IgnoreParens();
665 // For GNU extension '?:' operator, the left hand side will be an
666 // OpaqueValueExpr, so get the underlying expression.
667 if (const OpaqueValueExpr *OpaqueEx = dyn_cast<OpaqueValueExpr>(L))
668 L = OpaqueEx->getSourceExpr();
670 // If the last expression in the predecessor block matches true or false
671 // subexpression, get its the value.
672 if (ValEx == L->IgnoreParens() || ValEx == R->IgnoreParens()) {
674 V = SrcState->getSVal(ValEx, LCtx);
681 V = svalBuilder.conjureSymbolVal(0, Ex, LCtx, currBldrCtx->blockCount());
683 // Generate a new node with the binding from the appropriate path.
684 B.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V, true));
688 VisitOffsetOfExpr(const OffsetOfExpr *OOE,
689 ExplodedNode *Pred, ExplodedNodeSet &Dst) {
690 StmtNodeBuilder B(Pred, Dst, *currBldrCtx);
692 if (OOE->EvaluateAsInt(IV, getContext())) {
693 assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
694 assert(OOE->getType()->isBuiltinType());
695 assert(OOE->getType()->getAs<BuiltinType>()->isInteger());
696 assert(IV.isSigned() == OOE->getType()->isSignedIntegerType());
697 SVal X = svalBuilder.makeIntVal(IV);
698 B.generateNode(OOE, Pred,
699 Pred->getState()->BindExpr(OOE, Pred->getLocationContext(),
702 // FIXME: Handle the case where __builtin_offsetof is not a constant.
707 VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *Ex,
709 ExplodedNodeSet &Dst) {
710 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
712 QualType T = Ex->getTypeOfArgument();
714 if (Ex->getKind() == UETT_SizeOf) {
715 if (!T->isIncompleteType() && !T->isConstantSizeType()) {
716 assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
718 // FIXME: Add support for VLA type arguments and VLA expressions.
719 // When that happens, we should probably refactor VLASizeChecker's code.
722 else if (T->getAs<ObjCObjectType>()) {
723 // Some code tries to take the sizeof an ObjCObjectType, relying that
724 // the compiler has laid out its representation. Just report Unknown
730 APSInt Value = Ex->EvaluateKnownConstInt(getContext());
731 CharUnits amt = CharUnits::fromQuantity(Value.getZExtValue());
733 ProgramStateRef state = Pred->getState();
734 state = state->BindExpr(Ex, Pred->getLocationContext(),
735 svalBuilder.makeIntVal(amt.getQuantity(),
737 Bldr.generateNode(Ex, Pred, state);
740 void ExprEngine::VisitUnaryOperator(const UnaryOperator* U,
742 ExplodedNodeSet &Dst) {
743 // FIXME: Prechecks eventually go in ::Visit().
744 ExplodedNodeSet CheckedSet;
745 getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, U, *this);
747 ExplodedNodeSet EvalSet;
748 StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
750 for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
752 switch (U->getOpcode()) {
756 VisitIncrementDecrementOperator(U, *I, Tmp);
761 const Expr *Ex = U->getSubExpr()->IgnoreParens();
763 // FIXME: We don't have complex SValues yet.
764 if (Ex->getType()->isAnyComplexType()) {
765 // Just report "Unknown."
769 // For all other types, UO_Real is an identity operation.
770 assert (U->getType() == Ex->getType());
771 ProgramStateRef state = (*I)->getState();
772 const LocationContext *LCtx = (*I)->getLocationContext();
773 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
774 state->getSVal(Ex, LCtx)));
779 const Expr *Ex = U->getSubExpr()->IgnoreParens();
780 // FIXME: We don't have complex SValues yet.
781 if (Ex->getType()->isAnyComplexType()) {
782 // Just report "Unknown."
785 // For all other types, UO_Imag returns 0.
786 ProgramStateRef state = (*I)->getState();
787 const LocationContext *LCtx = (*I)->getLocationContext();
788 SVal X = svalBuilder.makeZeroVal(Ex->getType());
789 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, X));
794 assert(!U->isGLValue());
799 // FIXME: We can probably just have some magic in Environment::getSVal()
800 // that propagates values, instead of creating a new node here.
802 // Unary "+" is a no-op, similar to a parentheses. We still have places
803 // where it may be a block-level expression, so we need to
804 // generate an extra node that just propagates the value of the
806 const Expr *Ex = U->getSubExpr()->IgnoreParens();
807 ProgramStateRef state = (*I)->getState();
808 const LocationContext *LCtx = (*I)->getLocationContext();
809 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx,
810 state->getSVal(Ex, LCtx)));
817 assert (!U->isGLValue());
818 const Expr *Ex = U->getSubExpr()->IgnoreParens();
819 ProgramStateRef state = (*I)->getState();
820 const LocationContext *LCtx = (*I)->getLocationContext();
822 // Get the value of the subexpression.
823 SVal V = state->getSVal(Ex, LCtx);
825 if (V.isUnknownOrUndef()) {
826 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V));
830 switch (U->getOpcode()) {
832 llvm_unreachable("Invalid Opcode.");
834 // FIXME: Do we need to handle promotions?
835 state = state->BindExpr(U, LCtx, evalComplement(V.castAs<NonLoc>()));
838 // FIXME: Do we need to handle promotions?
839 state = state->BindExpr(U, LCtx, evalMinus(V.castAs<NonLoc>()));
842 // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
844 // Note: technically we do "E == 0", but this is the same in the
845 // transfer functions as "0 == E".
847 if (Optional<Loc> LV = V.getAs<Loc>()) {
848 Loc X = svalBuilder.makeNull();
849 Result = evalBinOp(state, BO_EQ, *LV, X, U->getType());
851 else if (Ex->getType()->isFloatingType()) {
852 // FIXME: handle floating point types.
853 Result = UnknownVal();
855 nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
856 Result = evalBinOp(state, BO_EQ, V.castAs<NonLoc>(), X,
860 state = state->BindExpr(U, LCtx, Result);
863 Bldr.generateNode(U, *I, state);
869 getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, U, *this);
872 void ExprEngine::VisitIncrementDecrementOperator(const UnaryOperator* U,
874 ExplodedNodeSet &Dst) {
875 // Handle ++ and -- (both pre- and post-increment).
876 assert (U->isIncrementDecrementOp());
877 const Expr *Ex = U->getSubExpr()->IgnoreParens();
879 const LocationContext *LCtx = Pred->getLocationContext();
880 ProgramStateRef state = Pred->getState();
881 SVal loc = state->getSVal(Ex, LCtx);
885 evalLoad(Tmp, U, Ex, Pred, state, loc);
887 ExplodedNodeSet Dst2;
888 StmtNodeBuilder Bldr(Tmp, Dst2, *currBldrCtx);
889 for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end();I!=E;++I) {
891 state = (*I)->getState();
892 assert(LCtx == (*I)->getLocationContext());
893 SVal V2_untested = state->getSVal(Ex, LCtx);
895 // Propagate unknown and undefined values.
896 if (V2_untested.isUnknownOrUndef()) {
897 Bldr.generateNode(U, *I, state->BindExpr(U, LCtx, V2_untested));
900 DefinedSVal V2 = V2_untested.castAs<DefinedSVal>();
902 // Handle all other values.
903 BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add : BO_Sub;
905 // If the UnaryOperator has non-location type, use its type to create the
906 // constant value. If the UnaryOperator has location type, create the
907 // constant with int type and pointer width.
910 if (U->getType()->isAnyPointerType())
911 RHS = svalBuilder.makeArrayIndex(1);
912 else if (U->getType()->isIntegralOrEnumerationType())
913 RHS = svalBuilder.makeIntVal(1, U->getType());
917 SVal Result = evalBinOp(state, Op, V2, RHS, U->getType());
919 // Conjure a new symbol if necessary to recover precision.
920 if (Result.isUnknown()){
921 DefinedOrUnknownSVal SymVal =
922 svalBuilder.conjureSymbolVal(0, Ex, LCtx, currBldrCtx->blockCount());
925 // If the value is a location, ++/-- should always preserve
926 // non-nullness. Check if the original value was non-null, and if so
927 // propagate that constraint.
928 if (Loc::isLocType(U->getType())) {
929 DefinedOrUnknownSVal Constraint =
930 svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
932 if (!state->assume(Constraint, true)) {
933 // It isn't feasible for the original value to be null.
934 // Propagate this constraint.
935 Constraint = svalBuilder.evalEQ(state, SymVal,
936 svalBuilder.makeZeroVal(U->getType()));
939 state = state->assume(Constraint, false);
945 // Since the lvalue-to-rvalue conversion is explicit in the AST,
946 // we bind an l-value if the operator is prefix and an lvalue (in C++).
948 state = state->BindExpr(U, LCtx, loc);
950 state = state->BindExpr(U, LCtx, U->isPostfix() ? V2 : Result);
952 // Perform the store.
954 ExplodedNodeSet Dst3;
955 evalStore(Dst3, U, U, *I, state, loc, Result);