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