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