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