1 //===- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines a meta-engine for path-sensitive dataflow analysis that
10 //  is built on GREngine, but provides the boilerplate to execute transfer
11 //  functions and build the ExplodedGraph at the expression level.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
16 #include "PrettyStackTraceLocationContext.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclBase.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ParentMap.h"
26 #include "clang/AST/PrettyPrinter.h"
27 #include "clang/AST/Stmt.h"
28 #include "clang/AST/StmtCXX.h"
29 #include "clang/AST/StmtObjC.h"
30 #include "clang/AST/Type.h"
31 #include "clang/Analysis/AnalysisDeclContext.h"
32 #include "clang/Analysis/CFG.h"
33 #include "clang/Analysis/ConstructionContext.h"
34 #include "clang/Analysis/ProgramPoint.h"
35 #include "clang/Basic/IdentifierTable.h"
36 #include "clang/Basic/LLVM.h"
37 #include "clang/Basic/LangOptions.h"
38 #include "clang/Basic/PrettyStackTrace.h"
39 #include "clang/Basic/SourceLocation.h"
40 #include "clang/Basic/SourceManager.h"
41 #include "clang/Basic/Specifiers.h"
42 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
43 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
44 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
45 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
46 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
47 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
48 #include "clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h"
49 #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
50 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
51 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h"
52 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
53 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
54 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
55 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
56 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
57 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
58 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
59 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
60 #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
61 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
62 #include "llvm/ADT/APSInt.h"
63 #include "llvm/ADT/DenseMap.h"
64 #include "llvm/ADT/ImmutableMap.h"
65 #include "llvm/ADT/ImmutableSet.h"
66 #include "llvm/ADT/Optional.h"
67 #include "llvm/ADT/SmallVector.h"
68 #include "llvm/ADT/Statistic.h"
69 #include "llvm/Support/Casting.h"
70 #include "llvm/Support/Compiler.h"
71 #include "llvm/Support/DOTGraphTraits.h"
72 #include "llvm/Support/ErrorHandling.h"
73 #include "llvm/Support/GraphWriter.h"
74 #include "llvm/Support/SaveAndRestore.h"
75 #include "llvm/Support/raw_ostream.h"
76 #include <cassert>
77 #include <cstdint>
78 #include <memory>
79 #include <string>
80 #include <tuple>
81 #include <utility>
82 #include <vector>
83 
84 using namespace clang;
85 using namespace ento;
86 
87 #define DEBUG_TYPE "ExprEngine"
88 
89 STATISTIC(NumRemoveDeadBindings,
90             "The # of times RemoveDeadBindings is called");
91 STATISTIC(NumMaxBlockCountReached,
92             "The # of aborted paths due to reaching the maximum block count in "
93             "a top level function");
94 STATISTIC(NumMaxBlockCountReachedInInlined,
95             "The # of aborted paths due to reaching the maximum block count in "
96             "an inlined function");
97 STATISTIC(NumTimesRetriedWithoutInlining,
98             "The # of times we re-evaluated a call without inlining");
99 
100 //===----------------------------------------------------------------------===//
101 // Internal program state traits.
102 //===----------------------------------------------------------------------===//
103 
104 namespace {
105 
106 // When modeling a C++ constructor, for a variety of reasons we need to track
107 // the location of the object for the duration of its ConstructionContext.
108 // ObjectsUnderConstruction maps statements within the construction context
109 // to the object's location, so that on every such statement the location
110 // could have been retrieved.
111 
112 /// ConstructedObjectKey is used for being able to find the path-sensitive
113 /// memory region of a freshly constructed object while modeling the AST node
114 /// that syntactically represents the object that is being constructed.
115 /// Semantics of such nodes may sometimes require access to the region that's
116 /// not otherwise present in the program state, or to the very fact that
117 /// the construction context was present and contained references to these
118 /// AST nodes.
119 class ConstructedObjectKey {
120   typedef std::pair<ConstructionContextItem, const LocationContext *>
121       ConstructedObjectKeyImpl;
122 
123   const ConstructedObjectKeyImpl Impl;
124 
125   const void *getAnyASTNodePtr() const {
126     if (const Stmt *S = getItem().getStmtOrNull())
127       return S;
128     else
129       return getItem().getCXXCtorInitializer();
130   }
131 
132 public:
133   explicit ConstructedObjectKey(const ConstructionContextItem &Item,
134                        const LocationContext *LC)
135       : Impl(Item, LC) {}
136 
137   const ConstructionContextItem &getItem() const { return Impl.first; }
138   const LocationContext *getLocationContext() const { return Impl.second; }
139 
140   ASTContext &getASTContext() const {
141     return getLocationContext()->getDecl()->getASTContext();
142   }
143 
144   void print(llvm::raw_ostream &OS, PrinterHelper *Helper, PrintingPolicy &PP) {
145     OS << "(LC" << getLocationContext()->getID() << ',';
146     if (const Stmt *S = getItem().getStmtOrNull())
147       OS << 'S' << S->getID(getASTContext());
148     else
149       OS << 'I' << getItem().getCXXCtorInitializer()->getID(getASTContext());
150     OS << ',' << getItem().getKindAsString();
151     if (getItem().getKind() == ConstructionContextItem::ArgumentKind)
152       OS << " #" << getItem().getIndex();
153     OS << ") ";
154     if (const Stmt *S = getItem().getStmtOrNull()) {
155       S->printPretty(OS, Helper, PP);
156     } else {
157       const CXXCtorInitializer *I = getItem().getCXXCtorInitializer();
158       OS << I->getAnyMember()->getNameAsString();
159     }
160   }
161 
162   void Profile(llvm::FoldingSetNodeID &ID) const {
163     ID.Add(Impl.first);
164     ID.AddPointer(Impl.second);
165   }
166 
167   bool operator==(const ConstructedObjectKey &RHS) const {
168     return Impl == RHS.Impl;
169   }
170 
171   bool operator<(const ConstructedObjectKey &RHS) const {
172     return Impl < RHS.Impl;
173   }
174 };
175 } // namespace
176 
177 typedef llvm::ImmutableMap<ConstructedObjectKey, SVal>
178     ObjectsUnderConstructionMap;
179 REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction,
180                                  ObjectsUnderConstructionMap)
181 
182 //===----------------------------------------------------------------------===//
183 // Engine construction and deletion.
184 //===----------------------------------------------------------------------===//
185 
186 static const char* TagProviderName = "ExprEngine";
187 
188 ExprEngine::ExprEngine(cross_tu::CrossTranslationUnitContext &CTU,
189                        AnalysisManager &mgr,
190                        SetOfConstDecls *VisitedCalleesIn,
191                        FunctionSummariesTy *FS,
192                        InliningModes HowToInlineIn)
193     : CTU(CTU), AMgr(mgr),
194       AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
195       Engine(*this, FS, mgr.getAnalyzerOptions()), G(Engine.getGraph()),
196       StateMgr(getContext(), mgr.getStoreManagerCreator(),
197                mgr.getConstraintManagerCreator(), G.getAllocator(),
198                this),
199       SymMgr(StateMgr.getSymbolManager()),
200       MRMgr(StateMgr.getRegionManager()),
201       svalBuilder(StateMgr.getSValBuilder()),
202       ObjCNoRet(mgr.getASTContext()),
203       BR(mgr, *this),
204       VisitedCallees(VisitedCalleesIn),
205       HowToInline(HowToInlineIn)
206   {
207   unsigned TrimInterval = mgr.options.GraphTrimInterval;
208   if (TrimInterval != 0) {
209     // Enable eager node reclamation when constructing the ExplodedGraph.
210     G.enableNodeReclamation(TrimInterval);
211   }
212 }
213 
214 ExprEngine::~ExprEngine() {
215   BR.FlushReports();
216 }
217 
218 //===----------------------------------------------------------------------===//
219 // Utility methods.
220 //===----------------------------------------------------------------------===//
221 
222 ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
223   ProgramStateRef state = StateMgr.getInitialState(InitLoc);
224   const Decl *D = InitLoc->getDecl();
225 
226   // Preconditions.
227   // FIXME: It would be nice if we had a more general mechanism to add
228   // such preconditions.  Some day.
229   do {
230     if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
231       // Precondition: the first argument of 'main' is an integer guaranteed
232       //  to be > 0.
233       const IdentifierInfo *II = FD->getIdentifier();
234       if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
235         break;
236 
237       const ParmVarDecl *PD = FD->getParamDecl(0);
238       QualType T = PD->getType();
239       const auto *BT = dyn_cast<BuiltinType>(T);
240       if (!BT || !BT->isInteger())
241         break;
242 
243       const MemRegion *R = state->getRegion(PD, InitLoc);
244       if (!R)
245         break;
246 
247       SVal V = state->getSVal(loc::MemRegionVal(R));
248       SVal Constraint_untested = evalBinOp(state, BO_GT, V,
249                                            svalBuilder.makeZeroVal(T),
250                                            svalBuilder.getConditionType());
251 
252       Optional<DefinedOrUnknownSVal> Constraint =
253           Constraint_untested.getAs<DefinedOrUnknownSVal>();
254 
255       if (!Constraint)
256         break;
257 
258       if (ProgramStateRef newState = state->assume(*Constraint, true))
259         state = newState;
260     }
261     break;
262   }
263   while (false);
264 
265   if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
266     // Precondition: 'self' is always non-null upon entry to an Objective-C
267     // method.
268     const ImplicitParamDecl *SelfD = MD->getSelfDecl();
269     const MemRegion *R = state->getRegion(SelfD, InitLoc);
270     SVal V = state->getSVal(loc::MemRegionVal(R));
271 
272     if (Optional<Loc> LV = V.getAs<Loc>()) {
273       // Assume that the pointer value in 'self' is non-null.
274       state = state->assume(*LV, true);
275       assert(state && "'self' cannot be null");
276     }
277   }
278 
279   if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
280     if (!MD->isStatic()) {
281       // Precondition: 'this' is always non-null upon entry to the
282       // top-level function.  This is our starting assumption for
283       // analyzing an "open" program.
284       const StackFrameContext *SFC = InitLoc->getStackFrame();
285       if (SFC->getParent() == nullptr) {
286         loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
287         SVal V = state->getSVal(L);
288         if (Optional<Loc> LV = V.getAs<Loc>()) {
289           state = state->assume(*LV, true);
290           assert(state && "'this' cannot be null");
291         }
292       }
293     }
294   }
295 
296   return state;
297 }
298 
299 ProgramStateRef ExprEngine::createTemporaryRegionIfNeeded(
300     ProgramStateRef State, const LocationContext *LC,
301     const Expr *InitWithAdjustments, const Expr *Result,
302     const SubRegion **OutRegionWithAdjustments) {
303   // FIXME: This function is a hack that works around the quirky AST
304   // we're often having with respect to C++ temporaries. If only we modelled
305   // the actual execution order of statements properly in the CFG,
306   // all the hassle with adjustments would not be necessary,
307   // and perhaps the whole function would be removed.
308   SVal InitValWithAdjustments = State->getSVal(InitWithAdjustments, LC);
309   if (!Result) {
310     // If we don't have an explicit result expression, we're in "if needed"
311     // mode. Only create a region if the current value is a NonLoc.
312     if (!InitValWithAdjustments.getAs<NonLoc>()) {
313       if (OutRegionWithAdjustments)
314         *OutRegionWithAdjustments = nullptr;
315       return State;
316     }
317     Result = InitWithAdjustments;
318   } else {
319     // We need to create a region no matter what. For sanity, make sure we don't
320     // try to stuff a Loc into a non-pointer temporary region.
321     assert(!InitValWithAdjustments.getAs<Loc>() ||
322            Loc::isLocType(Result->getType()) ||
323            Result->getType()->isMemberPointerType());
324   }
325 
326   ProgramStateManager &StateMgr = State->getStateManager();
327   MemRegionManager &MRMgr = StateMgr.getRegionManager();
328   StoreManager &StoreMgr = StateMgr.getStoreManager();
329 
330   // MaterializeTemporaryExpr may appear out of place, after a few field and
331   // base-class accesses have been made to the object, even though semantically
332   // it is the whole object that gets materialized and lifetime-extended.
333   //
334   // For example:
335   //
336   //   `-MaterializeTemporaryExpr
337   //     `-MemberExpr
338   //       `-CXXTemporaryObjectExpr
339   //
340   // instead of the more natural
341   //
342   //   `-MemberExpr
343   //     `-MaterializeTemporaryExpr
344   //       `-CXXTemporaryObjectExpr
345   //
346   // Use the usual methods for obtaining the expression of the base object,
347   // and record the adjustments that we need to make to obtain the sub-object
348   // that the whole expression 'Ex' refers to. This trick is usual,
349   // in the sense that CodeGen takes a similar route.
350 
351   SmallVector<const Expr *, 2> CommaLHSs;
352   SmallVector<SubobjectAdjustment, 2> Adjustments;
353 
354   const Expr *Init = InitWithAdjustments->skipRValueSubobjectAdjustments(
355       CommaLHSs, Adjustments);
356 
357   // Take the region for Init, i.e. for the whole object. If we do not remember
358   // the region in which the object originally was constructed, come up with
359   // a new temporary region out of thin air and copy the contents of the object
360   // (which are currently present in the Environment, because Init is an rvalue)
361   // into that region. This is not correct, but it is better than nothing.
362   const TypedValueRegion *TR = nullptr;
363   if (const auto *MT = dyn_cast<MaterializeTemporaryExpr>(Result)) {
364     if (Optional<SVal> V = getObjectUnderConstruction(State, MT, LC)) {
365       State = finishObjectConstruction(State, MT, LC);
366       State = State->BindExpr(Result, LC, *V);
367       return State;
368     } else {
369       StorageDuration SD = MT->getStorageDuration();
370       // If this object is bound to a reference with static storage duration, we
371       // put it in a different region to prevent "address leakage" warnings.
372       if (SD == SD_Static || SD == SD_Thread) {
373         TR = MRMgr.getCXXStaticTempObjectRegion(Init);
374       } else {
375         TR = MRMgr.getCXXTempObjectRegion(Init, LC);
376       }
377     }
378   } else {
379     TR = MRMgr.getCXXTempObjectRegion(Init, LC);
380   }
381 
382   SVal Reg = loc::MemRegionVal(TR);
383   SVal BaseReg = Reg;
384 
385   // Make the necessary adjustments to obtain the sub-object.
386   for (auto I = Adjustments.rbegin(), E = Adjustments.rend(); I != E; ++I) {
387     const SubobjectAdjustment &Adj = *I;
388     switch (Adj.Kind) {
389     case SubobjectAdjustment::DerivedToBaseAdjustment:
390       Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath);
391       break;
392     case SubobjectAdjustment::FieldAdjustment:
393       Reg = StoreMgr.getLValueField(Adj.Field, Reg);
394       break;
395     case SubobjectAdjustment::MemberPointerAdjustment:
396       // FIXME: Unimplemented.
397       State = State->invalidateRegions(Reg, InitWithAdjustments,
398                                        currBldrCtx->blockCount(), LC, true,
399                                        nullptr, nullptr, nullptr);
400       return State;
401     }
402   }
403 
404   // What remains is to copy the value of the object to the new region.
405   // FIXME: In other words, what we should always do is copy value of the
406   // Init expression (which corresponds to the bigger object) to the whole
407   // temporary region TR. However, this value is often no longer present
408   // in the Environment. If it has disappeared, we instead invalidate TR.
409   // Still, what we can do is assign the value of expression Ex (which
410   // corresponds to the sub-object) to the TR's sub-region Reg. At least,
411   // values inside Reg would be correct.
412   SVal InitVal = State->getSVal(Init, LC);
413   if (InitVal.isUnknown()) {
414     InitVal = getSValBuilder().conjureSymbolVal(Result, LC, Init->getType(),
415                                                 currBldrCtx->blockCount());
416     State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
417 
418     // Then we'd need to take the value that certainly exists and bind it
419     // over.
420     if (InitValWithAdjustments.isUnknown()) {
421       // Try to recover some path sensitivity in case we couldn't
422       // compute the value.
423       InitValWithAdjustments = getSValBuilder().conjureSymbolVal(
424           Result, LC, InitWithAdjustments->getType(),
425           currBldrCtx->blockCount());
426     }
427     State =
428         State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, LC, false);
429   } else {
430     State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
431   }
432 
433   // The result expression would now point to the correct sub-region of the
434   // newly created temporary region. Do this last in order to getSVal of Init
435   // correctly in case (Result == Init).
436   if (Result->isGLValue()) {
437     State = State->BindExpr(Result, LC, Reg);
438   } else {
439     State = State->BindExpr(Result, LC, InitValWithAdjustments);
440   }
441 
442   // Notify checkers once for two bindLoc()s.
443   State = processRegionChange(State, TR, LC);
444 
445   if (OutRegionWithAdjustments)
446     *OutRegionWithAdjustments = cast<SubRegion>(Reg.getAsRegion());
447   return State;
448 }
449 
450 ProgramStateRef
451 ExprEngine::addObjectUnderConstruction(ProgramStateRef State,
452                                        const ConstructionContextItem &Item,
453                                        const LocationContext *LC, SVal V) {
454   ConstructedObjectKey Key(Item, LC->getStackFrame());
455   // FIXME: Currently the state might already contain the marker due to
456   // incorrect handling of temporaries bound to default parameters.
457   assert(!State->get<ObjectsUnderConstruction>(Key) ||
458          Key.getItem().getKind() ==
459              ConstructionContextItem::TemporaryDestructorKind);
460   return State->set<ObjectsUnderConstruction>(Key, V);
461 }
462 
463 Optional<SVal>
464 ExprEngine::getObjectUnderConstruction(ProgramStateRef State,
465                                        const ConstructionContextItem &Item,
466                                        const LocationContext *LC) {
467   ConstructedObjectKey Key(Item, LC->getStackFrame());
468   return Optional<SVal>::create(State->get<ObjectsUnderConstruction>(Key));
469 }
470 
471 ProgramStateRef
472 ExprEngine::finishObjectConstruction(ProgramStateRef State,
473                                      const ConstructionContextItem &Item,
474                                      const LocationContext *LC) {
475   ConstructedObjectKey Key(Item, LC->getStackFrame());
476   assert(State->contains<ObjectsUnderConstruction>(Key));
477   return State->remove<ObjectsUnderConstruction>(Key);
478 }
479 
480 ProgramStateRef ExprEngine::elideDestructor(ProgramStateRef State,
481                                             const CXXBindTemporaryExpr *BTE,
482                                             const LocationContext *LC) {
483   ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
484   // FIXME: Currently the state might already contain the marker due to
485   // incorrect handling of temporaries bound to default parameters.
486   return State->set<ObjectsUnderConstruction>(Key, UnknownVal());
487 }
488 
489 ProgramStateRef
490 ExprEngine::cleanupElidedDestructor(ProgramStateRef State,
491                                     const CXXBindTemporaryExpr *BTE,
492                                     const LocationContext *LC) {
493   ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
494   assert(State->contains<ObjectsUnderConstruction>(Key));
495   return State->remove<ObjectsUnderConstruction>(Key);
496 }
497 
498 bool ExprEngine::isDestructorElided(ProgramStateRef State,
499                                     const CXXBindTemporaryExpr *BTE,
500                                     const LocationContext *LC) {
501   ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
502   return State->contains<ObjectsUnderConstruction>(Key);
503 }
504 
505 bool ExprEngine::areAllObjectsFullyConstructed(ProgramStateRef State,
506                                                const LocationContext *FromLC,
507                                                const LocationContext *ToLC) {
508   const LocationContext *LC = FromLC;
509   while (LC != ToLC) {
510     assert(LC && "ToLC must be a parent of FromLC!");
511     for (auto I : State->get<ObjectsUnderConstruction>())
512       if (I.first.getLocationContext() == LC)
513         return false;
514 
515     LC = LC->getParent();
516   }
517   return true;
518 }
519 
520 
521 //===----------------------------------------------------------------------===//
522 // Top-level transfer function logic (Dispatcher).
523 //===----------------------------------------------------------------------===//
524 
525 /// evalAssume - Called by ConstraintManager. Used to call checker-specific
526 ///  logic for handling assumptions on symbolic values.
527 ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
528                                               SVal cond, bool assumption) {
529   return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
530 }
531 
532 ProgramStateRef
533 ExprEngine::processRegionChanges(ProgramStateRef state,
534                                  const InvalidatedSymbols *invalidated,
535                                  ArrayRef<const MemRegion *> Explicits,
536                                  ArrayRef<const MemRegion *> Regions,
537                                  const LocationContext *LCtx,
538                                  const CallEvent *Call) {
539   return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
540                                                          Explicits, Regions,
541                                                          LCtx, Call);
542 }
543 
544 static void printObjectsUnderConstructionForContext(raw_ostream &Out,
545                                                     ProgramStateRef State,
546                                                     const char *NL,
547                                                     const LocationContext *LC) {
548   PrintingPolicy PP =
549       LC->getAnalysisDeclContext()->getASTContext().getPrintingPolicy();
550   for (auto I : State->get<ObjectsUnderConstruction>()) {
551     ConstructedObjectKey Key = I.first;
552     SVal Value = I.second;
553     if (Key.getLocationContext() != LC)
554       continue;
555     Key.print(Out, nullptr, PP);
556     Out << " : " << Value << NL;
557   }
558 }
559 
560 void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
561                             const char *NL, const char *Sep,
562                             const LocationContext *LCtx) {
563   if (LCtx) {
564     if (!State->get<ObjectsUnderConstruction>().isEmpty()) {
565       Out << Sep << "Objects under construction:" << NL;
566 
567       LCtx->dumpStack(Out, "", NL, Sep, [&](const LocationContext *LC) {
568         printObjectsUnderConstructionForContext(Out, State, NL, LC);
569       });
570     }
571   }
572 
573   getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
574 }
575 
576 void ExprEngine::processEndWorklist() {
577   getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
578 }
579 
580 void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
581                                    unsigned StmtIdx, NodeBuilderContext *Ctx) {
582   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
583   currStmtIdx = StmtIdx;
584   currBldrCtx = Ctx;
585 
586   switch (E.getKind()) {
587     case CFGElement::Statement:
588     case CFGElement::Constructor:
589     case CFGElement::CXXRecordTypedCall:
590       ProcessStmt(E.castAs<CFGStmt>().getStmt(), Pred);
591       return;
592     case CFGElement::Initializer:
593       ProcessInitializer(E.castAs<CFGInitializer>(), Pred);
594       return;
595     case CFGElement::NewAllocator:
596       ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(),
597                           Pred);
598       return;
599     case CFGElement::AutomaticObjectDtor:
600     case CFGElement::DeleteDtor:
601     case CFGElement::BaseDtor:
602     case CFGElement::MemberDtor:
603     case CFGElement::TemporaryDtor:
604       ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred);
605       return;
606     case CFGElement::LoopExit:
607       ProcessLoopExit(E.castAs<CFGLoopExit>().getLoopStmt(), Pred);
608       return;
609     case CFGElement::LifetimeEnds:
610     case CFGElement::ScopeBegin:
611     case CFGElement::ScopeEnd:
612       return;
613   }
614 }
615 
616 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
617                                      const Stmt *S,
618                                      const ExplodedNode *Pred,
619                                      const LocationContext *LC) {
620   // Are we never purging state values?
621   if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
622     return false;
623 
624   // Is this the beginning of a basic block?
625   if (Pred->getLocation().getAs<BlockEntrance>())
626     return true;
627 
628   // Is this on a non-expression?
629   if (!isa<Expr>(S))
630     return true;
631 
632   // Run before processing a call.
633   if (CallEvent::isCallStmt(S))
634     return true;
635 
636   // Is this an expression that is consumed by another expression?  If so,
637   // postpone cleaning out the state.
638   ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
639   return !PM.isConsumedExpr(cast<Expr>(S));
640 }
641 
642 void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
643                             const Stmt *ReferenceStmt,
644                             const LocationContext *LC,
645                             const Stmt *DiagnosticStmt,
646                             ProgramPoint::Kind K) {
647   assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
648           ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
649           && "PostStmt is not generally supported by the SymbolReaper yet");
650   assert(LC && "Must pass the current (or expiring) LocationContext");
651 
652   if (!DiagnosticStmt) {
653     DiagnosticStmt = ReferenceStmt;
654     assert(DiagnosticStmt && "Required for clearing a LocationContext");
655   }
656 
657   NumRemoveDeadBindings++;
658   ProgramStateRef CleanedState = Pred->getState();
659 
660   // LC is the location context being destroyed, but SymbolReaper wants a
661   // location context that is still live. (If this is the top-level stack
662   // frame, this will be null.)
663   if (!ReferenceStmt) {
664     assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
665            "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
666     LC = LC->getParent();
667   }
668 
669   const StackFrameContext *SFC = LC ? LC->getStackFrame() : nullptr;
670   SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
671 
672   for (auto I : CleanedState->get<ObjectsUnderConstruction>()) {
673     if (SymbolRef Sym = I.second.getAsSymbol())
674       SymReaper.markLive(Sym);
675     if (const MemRegion *MR = I.second.getAsRegion())
676       SymReaper.markLive(MR);
677   }
678 
679   getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
680 
681   // Create a state in which dead bindings are removed from the environment
682   // and the store. TODO: The function should just return new env and store,
683   // not a new state.
684   CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
685 
686   // Process any special transfer function for dead symbols.
687   // A tag to track convenience transitions, which can be removed at cleanup.
688   static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
689   // Call checkers with the non-cleaned state so that they could query the
690   // values of the soon to be dead symbols.
691   ExplodedNodeSet CheckedSet;
692   getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
693                                                 DiagnosticStmt, *this, K);
694 
695   // For each node in CheckedSet, generate CleanedNodes that have the
696   // environment, the store, and the constraints cleaned up but have the
697   // user-supplied states as the predecessors.
698   StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
699   for (const auto I : CheckedSet) {
700     ProgramStateRef CheckerState = I->getState();
701 
702     // The constraint manager has not been cleaned up yet, so clean up now.
703     CheckerState =
704         getConstraintManager().removeDeadBindings(CheckerState, SymReaper);
705 
706     assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
707            "Checkers are not allowed to modify the Environment as a part of "
708            "checkDeadSymbols processing.");
709     assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
710            "Checkers are not allowed to modify the Store as a part of "
711            "checkDeadSymbols processing.");
712 
713     // Create a state based on CleanedState with CheckerState GDM and
714     // generate a transition to that state.
715     ProgramStateRef CleanedCheckerSt =
716         StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
717     Bldr.generateNode(DiagnosticStmt, I, CleanedCheckerSt, &cleanupTag, K);
718   }
719 }
720 
721 void ExprEngine::ProcessStmt(const Stmt *currStmt, ExplodedNode *Pred) {
722   // Reclaim any unnecessary nodes in the ExplodedGraph.
723   G.reclaimRecentlyAllocatedNodes();
724 
725   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
726                                 currStmt->getBeginLoc(),
727                                 "Error evaluating statement");
728 
729   // Remove dead bindings and symbols.
730   ExplodedNodeSet CleanedStates;
731   if (shouldRemoveDeadBindings(AMgr, currStmt, Pred,
732                                Pred->getLocationContext())) {
733     removeDead(Pred, CleanedStates, currStmt,
734                                     Pred->getLocationContext());
735   } else
736     CleanedStates.Add(Pred);
737 
738   // Visit the statement.
739   ExplodedNodeSet Dst;
740   for (const auto I : CleanedStates) {
741     ExplodedNodeSet DstI;
742     // Visit the statement.
743     Visit(currStmt, I, DstI);
744     Dst.insert(DstI);
745   }
746 
747   // Enqueue the new nodes onto the work list.
748   Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
749 }
750 
751 void ExprEngine::ProcessLoopExit(const Stmt* S, ExplodedNode *Pred) {
752   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
753                                 S->getBeginLoc(),
754                                 "Error evaluating end of the loop");
755   ExplodedNodeSet Dst;
756   Dst.Add(Pred);
757   NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
758   ProgramStateRef NewState = Pred->getState();
759 
760   if(AMgr.options.ShouldUnrollLoops)
761     NewState = processLoopEnd(S, NewState);
762 
763   LoopExit PP(S, Pred->getLocationContext());
764   Bldr.generateNode(PP, NewState, Pred);
765   // Enqueue the new nodes onto the work list.
766   Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
767 }
768 
769 void ExprEngine::ProcessInitializer(const CFGInitializer CFGInit,
770                                     ExplodedNode *Pred) {
771   const CXXCtorInitializer *BMI = CFGInit.getInitializer();
772   const Expr *Init = BMI->getInit()->IgnoreImplicit();
773   const LocationContext *LC = Pred->getLocationContext();
774 
775   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
776                                 BMI->getSourceLocation(),
777                                 "Error evaluating initializer");
778 
779   // We don't clean up dead bindings here.
780   const auto *stackFrame = cast<StackFrameContext>(Pred->getLocationContext());
781   const auto *decl = cast<CXXConstructorDecl>(stackFrame->getDecl());
782 
783   ProgramStateRef State = Pred->getState();
784   SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
785 
786   ExplodedNodeSet Tmp;
787   SVal FieldLoc;
788 
789   // Evaluate the initializer, if necessary
790   if (BMI->isAnyMemberInitializer()) {
791     // Constructors build the object directly in the field,
792     // but non-objects must be copied in from the initializer.
793     if (getObjectUnderConstruction(State, BMI, LC)) {
794       // The field was directly constructed, so there is no need to bind.
795       // But we still need to stop tracking the object under construction.
796       State = finishObjectConstruction(State, BMI, LC);
797       NodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
798       PostStore PS(Init, LC, /*Loc*/ nullptr, /*tag*/ nullptr);
799       Bldr.generateNode(PS, State, Pred);
800     } else {
801       const ValueDecl *Field;
802       if (BMI->isIndirectMemberInitializer()) {
803         Field = BMI->getIndirectMember();
804         FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
805       } else {
806         Field = BMI->getMember();
807         FieldLoc = State->getLValue(BMI->getMember(), thisVal);
808       }
809 
810       SVal InitVal;
811       if (Init->getType()->isArrayType()) {
812         // Handle arrays of trivial type. We can represent this with a
813         // primitive load/copy from the base array region.
814         const ArraySubscriptExpr *ASE;
815         while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
816           Init = ASE->getBase()->IgnoreImplicit();
817 
818         SVal LValue = State->getSVal(Init, stackFrame);
819         if (!Field->getType()->isReferenceType())
820           if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
821             InitVal = State->getSVal(*LValueLoc);
822 
823         // If we fail to get the value for some reason, use a symbolic value.
824         if (InitVal.isUnknownOrUndef()) {
825           SValBuilder &SVB = getSValBuilder();
826           InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
827                                          Field->getType(),
828                                          currBldrCtx->blockCount());
829         }
830       } else {
831         InitVal = State->getSVal(BMI->getInit(), stackFrame);
832       }
833 
834       PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
835       evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
836     }
837   } else {
838     assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
839     Tmp.insert(Pred);
840     // We already did all the work when visiting the CXXConstructExpr.
841   }
842 
843   // Construct PostInitializer nodes whether the state changed or not,
844   // so that the diagnostics don't get confused.
845   PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
846   ExplodedNodeSet Dst;
847   NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
848   for (const auto I : Tmp) {
849     ProgramStateRef State = I->getState();
850     Bldr.generateNode(PP, State, I);
851   }
852 
853   // Enqueue the new nodes onto the work list.
854   Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
855 }
856 
857 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
858                                      ExplodedNode *Pred) {
859   ExplodedNodeSet Dst;
860   switch (D.getKind()) {
861   case CFGElement::AutomaticObjectDtor:
862     ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst);
863     break;
864   case CFGElement::BaseDtor:
865     ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
866     break;
867   case CFGElement::MemberDtor:
868     ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
869     break;
870   case CFGElement::TemporaryDtor:
871     ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst);
872     break;
873   case CFGElement::DeleteDtor:
874     ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
875     break;
876   default:
877     llvm_unreachable("Unexpected dtor kind.");
878   }
879 
880   // Enqueue the new nodes onto the work list.
881   Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
882 }
883 
884 void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE,
885                                      ExplodedNode *Pred) {
886   ExplodedNodeSet Dst;
887   AnalysisManager &AMgr = getAnalysisManager();
888   AnalyzerOptions &Opts = AMgr.options;
889   // TODO: We're not evaluating allocators for all cases just yet as
890   // we're not handling the return value correctly, which causes false
891   // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
892   if (Opts.MayInlineCXXAllocator)
893     VisitCXXNewAllocatorCall(NE, Pred, Dst);
894   else {
895     NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
896     const LocationContext *LCtx = Pred->getLocationContext();
897     PostImplicitCall PP(NE->getOperatorNew(), NE->getBeginLoc(), LCtx);
898     Bldr.generateNode(PP, Pred->getState(), Pred);
899   }
900   Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
901 }
902 
903 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
904                                          ExplodedNode *Pred,
905                                          ExplodedNodeSet &Dst) {
906   const VarDecl *varDecl = Dtor.getVarDecl();
907   QualType varType = varDecl->getType();
908 
909   ProgramStateRef state = Pred->getState();
910   SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
911   const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
912 
913   if (varType->isReferenceType()) {
914     const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion();
915     if (!ValueRegion) {
916       // FIXME: This should not happen. The language guarantees a presence
917       // of a valid initializer here, so the reference shall not be undefined.
918       // It seems that we're calling destructors over variables that
919       // were not initialized yet.
920       return;
921     }
922     Region = ValueRegion->getBaseRegion();
923     varType = cast<TypedValueRegion>(Region)->getValueType();
924   }
925 
926   // FIXME: We need to run the same destructor on every element of the array.
927   // This workaround will just run the first destructor (which will still
928   // invalidate the entire array).
929   EvalCallOptions CallOpts;
930   Region = makeZeroElementRegion(state, loc::MemRegionVal(Region), varType,
931                                  CallOpts.IsArrayCtorOrDtor).getAsRegion();
932 
933   VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
934                      Pred, Dst, CallOpts);
935 }
936 
937 void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor,
938                                    ExplodedNode *Pred,
939                                    ExplodedNodeSet &Dst) {
940   ProgramStateRef State = Pred->getState();
941   const LocationContext *LCtx = Pred->getLocationContext();
942   const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
943   const Stmt *Arg = DE->getArgument();
944   QualType DTy = DE->getDestroyedType();
945   SVal ArgVal = State->getSVal(Arg, LCtx);
946 
947   // If the argument to delete is known to be a null value,
948   // don't run destructor.
949   if (State->isNull(ArgVal).isConstrainedTrue()) {
950     QualType BTy = getContext().getBaseElementType(DTy);
951     const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
952     const CXXDestructorDecl *Dtor = RD->getDestructor();
953 
954     PostImplicitCall PP(Dtor, DE->getBeginLoc(), LCtx);
955     NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
956     Bldr.generateNode(PP, Pred->getState(), Pred);
957     return;
958   }
959 
960   EvalCallOptions CallOpts;
961   const MemRegion *ArgR = ArgVal.getAsRegion();
962   if (DE->isArrayForm()) {
963     // FIXME: We need to run the same destructor on every element of the array.
964     // This workaround will just run the first destructor (which will still
965     // invalidate the entire array).
966     CallOpts.IsArrayCtorOrDtor = true;
967     // Yes, it may even be a multi-dimensional array.
968     while (const auto *AT = getContext().getAsArrayType(DTy))
969       DTy = AT->getElementType();
970     if (ArgR)
971       ArgR = getStoreManager().GetElementZeroRegion(cast<SubRegion>(ArgR), DTy);
972   }
973 
974   VisitCXXDestructor(DTy, ArgR, DE, /*IsBase=*/false, Pred, Dst, CallOpts);
975 }
976 
977 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
978                                  ExplodedNode *Pred, ExplodedNodeSet &Dst) {
979   const LocationContext *LCtx = Pred->getLocationContext();
980 
981   const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
982   Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
983                                             LCtx->getStackFrame());
984   SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
985 
986   // Create the base object region.
987   const CXXBaseSpecifier *Base = D.getBaseSpecifier();
988   QualType BaseTy = Base->getType();
989   SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
990                                                      Base->isVirtual());
991 
992   VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(),
993                      CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst, {});
994 }
995 
996 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
997                                    ExplodedNode *Pred, ExplodedNodeSet &Dst) {
998   const FieldDecl *Member = D.getFieldDecl();
999   QualType T = Member->getType();
1000   ProgramStateRef State = Pred->getState();
1001   const LocationContext *LCtx = Pred->getLocationContext();
1002 
1003   const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
1004   Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
1005                                             LCtx->getStackFrame());
1006   SVal FieldVal =
1007       State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
1008 
1009   // FIXME: We need to run the same destructor on every element of the array.
1010   // This workaround will just run the first destructor (which will still
1011   // invalidate the entire array).
1012   EvalCallOptions CallOpts;
1013   FieldVal = makeZeroElementRegion(State, FieldVal, T,
1014                                    CallOpts.IsArrayCtorOrDtor);
1015 
1016   VisitCXXDestructor(T, FieldVal.castAs<loc::MemRegionVal>().getRegion(),
1017                      CurDtor->getBody(), /*IsBase=*/false, Pred, Dst, CallOpts);
1018 }
1019 
1020 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
1021                                       ExplodedNode *Pred,
1022                                       ExplodedNodeSet &Dst) {
1023   const CXXBindTemporaryExpr *BTE = D.getBindTemporaryExpr();
1024   ProgramStateRef State = Pred->getState();
1025   const LocationContext *LC = Pred->getLocationContext();
1026   const MemRegion *MR = nullptr;
1027 
1028   if (Optional<SVal> V =
1029           getObjectUnderConstruction(State, D.getBindTemporaryExpr(),
1030                                      Pred->getLocationContext())) {
1031     // FIXME: Currently we insert temporary destructors for default parameters,
1032     // but we don't insert the constructors, so the entry in
1033     // ObjectsUnderConstruction may be missing.
1034     State = finishObjectConstruction(State, D.getBindTemporaryExpr(),
1035                                      Pred->getLocationContext());
1036     MR = V->getAsRegion();
1037   }
1038 
1039   // If copy elision has occurred, and the constructor corresponding to the
1040   // destructor was elided, we need to skip the destructor as well.
1041   if (isDestructorElided(State, BTE, LC)) {
1042     State = cleanupElidedDestructor(State, BTE, LC);
1043     NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1044     PostImplicitCall PP(D.getDestructorDecl(getContext()),
1045                         D.getBindTemporaryExpr()->getBeginLoc(),
1046                         Pred->getLocationContext());
1047     Bldr.generateNode(PP, State, Pred);
1048     return;
1049   }
1050 
1051   ExplodedNodeSet CleanDtorState;
1052   StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx);
1053   StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State);
1054 
1055   QualType T = D.getBindTemporaryExpr()->getSubExpr()->getType();
1056   // FIXME: Currently CleanDtorState can be empty here due to temporaries being
1057   // bound to default parameters.
1058   assert(CleanDtorState.size() <= 1);
1059   ExplodedNode *CleanPred =
1060       CleanDtorState.empty() ? Pred : *CleanDtorState.begin();
1061 
1062   EvalCallOptions CallOpts;
1063   CallOpts.IsTemporaryCtorOrDtor = true;
1064   if (!MR) {
1065     CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
1066 
1067     // If we have no MR, we still need to unwrap the array to avoid destroying
1068     // the whole array at once. Regardless, we'd eventually need to model array
1069     // destructors properly, element-by-element.
1070     while (const ArrayType *AT = getContext().getAsArrayType(T)) {
1071       T = AT->getElementType();
1072       CallOpts.IsArrayCtorOrDtor = true;
1073     }
1074   } else {
1075     // We'd eventually need to makeZeroElementRegion() trick here,
1076     // but for now we don't have the respective construction contexts,
1077     // so MR would always be null in this case. Do nothing for now.
1078   }
1079   VisitCXXDestructor(T, MR, D.getBindTemporaryExpr(),
1080                      /*IsBase=*/false, CleanPred, Dst, CallOpts);
1081 }
1082 
1083 void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
1084                                                NodeBuilderContext &BldCtx,
1085                                                ExplodedNode *Pred,
1086                                                ExplodedNodeSet &Dst,
1087                                                const CFGBlock *DstT,
1088                                                const CFGBlock *DstF) {
1089   BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF);
1090   ProgramStateRef State = Pred->getState();
1091   const LocationContext *LC = Pred->getLocationContext();
1092   if (getObjectUnderConstruction(State, BTE, LC)) {
1093     TempDtorBuilder.markInfeasible(false);
1094     TempDtorBuilder.generateNode(State, true, Pred);
1095   } else {
1096     TempDtorBuilder.markInfeasible(true);
1097     TempDtorBuilder.generateNode(State, false, Pred);
1098   }
1099 }
1100 
1101 void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE,
1102                                            ExplodedNodeSet &PreVisit,
1103                                            ExplodedNodeSet &Dst) {
1104   // This is a fallback solution in case we didn't have a construction
1105   // context when we were constructing the temporary. Otherwise the map should
1106   // have been populated there.
1107   if (!getAnalysisManager().options.ShouldIncludeTemporaryDtorsInCFG) {
1108     // In case we don't have temporary destructors in the CFG, do not mark
1109     // the initialization - we would otherwise never clean it up.
1110     Dst = PreVisit;
1111     return;
1112   }
1113   StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx);
1114   for (ExplodedNode *Node : PreVisit) {
1115     ProgramStateRef State = Node->getState();
1116     const LocationContext *LC = Node->getLocationContext();
1117     if (!getObjectUnderConstruction(State, BTE, LC)) {
1118       // FIXME: Currently the state might also already contain the marker due to
1119       // incorrect handling of temporaries bound to default parameters; for
1120       // those, we currently skip the CXXBindTemporaryExpr but rely on adding
1121       // temporary destructor nodes.
1122       State = addObjectUnderConstruction(State, BTE, LC, UnknownVal());
1123     }
1124     StmtBldr.generateNode(BTE, Node, State);
1125   }
1126 }
1127 
1128 ProgramStateRef ExprEngine::escapeValue(ProgramStateRef State, SVal V,
1129                                         PointerEscapeKind K) const {
1130   class CollectReachableSymbolsCallback final : public SymbolVisitor {
1131     InvalidatedSymbols Symbols;
1132 
1133   public:
1134     explicit CollectReachableSymbolsCallback(ProgramStateRef) {}
1135 
1136     const InvalidatedSymbols &getSymbols() const { return Symbols; }
1137 
1138     bool VisitSymbol(SymbolRef Sym) override {
1139       Symbols.insert(Sym);
1140       return true;
1141     }
1142   };
1143 
1144   const CollectReachableSymbolsCallback &Scanner =
1145       State->scanReachableSymbols<CollectReachableSymbolsCallback>(V);
1146   return getCheckerManager().runCheckersForPointerEscape(
1147       State, Scanner.getSymbols(), /*CallEvent*/ nullptr, K, nullptr);
1148 }
1149 
1150 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
1151                        ExplodedNodeSet &DstTop) {
1152   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1153                                 S->getBeginLoc(), "Error evaluating statement");
1154   ExplodedNodeSet Dst;
1155   StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
1156 
1157   assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
1158 
1159   switch (S->getStmtClass()) {
1160     // C++, OpenMP and ARC stuff we don't support yet.
1161     case Expr::ObjCIndirectCopyRestoreExprClass:
1162     case Stmt::CXXDependentScopeMemberExprClass:
1163     case Stmt::CXXInheritedCtorInitExprClass:
1164     case Stmt::CXXTryStmtClass:
1165     case Stmt::CXXTypeidExprClass:
1166     case Stmt::CXXUuidofExprClass:
1167     case Stmt::CXXFoldExprClass:
1168     case Stmt::MSPropertyRefExprClass:
1169     case Stmt::MSPropertySubscriptExprClass:
1170     case Stmt::CXXUnresolvedConstructExprClass:
1171     case Stmt::DependentScopeDeclRefExprClass:
1172     case Stmt::ArrayTypeTraitExprClass:
1173     case Stmt::ExpressionTraitExprClass:
1174     case Stmt::UnresolvedLookupExprClass:
1175     case Stmt::UnresolvedMemberExprClass:
1176     case Stmt::TypoExprClass:
1177     case Stmt::CXXNoexceptExprClass:
1178     case Stmt::PackExpansionExprClass:
1179     case Stmt::SubstNonTypeTemplateParmPackExprClass:
1180     case Stmt::FunctionParmPackExprClass:
1181     case Stmt::CoroutineBodyStmtClass:
1182     case Stmt::CoawaitExprClass:
1183     case Stmt::DependentCoawaitExprClass:
1184     case Stmt::CoreturnStmtClass:
1185     case Stmt::CoyieldExprClass:
1186     case Stmt::SEHTryStmtClass:
1187     case Stmt::SEHExceptStmtClass:
1188     case Stmt::SEHLeaveStmtClass:
1189     case Stmt::SEHFinallyStmtClass:
1190     case Stmt::OMPParallelDirectiveClass:
1191     case Stmt::OMPSimdDirectiveClass:
1192     case Stmt::OMPForDirectiveClass:
1193     case Stmt::OMPForSimdDirectiveClass:
1194     case Stmt::OMPSectionsDirectiveClass:
1195     case Stmt::OMPSectionDirectiveClass:
1196     case Stmt::OMPSingleDirectiveClass:
1197     case Stmt::OMPMasterDirectiveClass:
1198     case Stmt::OMPCriticalDirectiveClass:
1199     case Stmt::OMPParallelForDirectiveClass:
1200     case Stmt::OMPParallelForSimdDirectiveClass:
1201     case Stmt::OMPParallelSectionsDirectiveClass:
1202     case Stmt::OMPTaskDirectiveClass:
1203     case Stmt::OMPTaskyieldDirectiveClass:
1204     case Stmt::OMPBarrierDirectiveClass:
1205     case Stmt::OMPTaskwaitDirectiveClass:
1206     case Stmt::OMPTaskgroupDirectiveClass:
1207     case Stmt::OMPFlushDirectiveClass:
1208     case Stmt::OMPOrderedDirectiveClass:
1209     case Stmt::OMPAtomicDirectiveClass:
1210     case Stmt::OMPTargetDirectiveClass:
1211     case Stmt::OMPTargetDataDirectiveClass:
1212     case Stmt::OMPTargetEnterDataDirectiveClass:
1213     case Stmt::OMPTargetExitDataDirectiveClass:
1214     case Stmt::OMPTargetParallelDirectiveClass:
1215     case Stmt::OMPTargetParallelForDirectiveClass:
1216     case Stmt::OMPTargetUpdateDirectiveClass:
1217     case Stmt::OMPTeamsDirectiveClass:
1218     case Stmt::OMPCancellationPointDirectiveClass:
1219     case Stmt::OMPCancelDirectiveClass:
1220     case Stmt::OMPTaskLoopDirectiveClass:
1221     case Stmt::OMPTaskLoopSimdDirectiveClass:
1222     case Stmt::OMPDistributeDirectiveClass:
1223     case Stmt::OMPDistributeParallelForDirectiveClass:
1224     case Stmt::OMPDistributeParallelForSimdDirectiveClass:
1225     case Stmt::OMPDistributeSimdDirectiveClass:
1226     case Stmt::OMPTargetParallelForSimdDirectiveClass:
1227     case Stmt::OMPTargetSimdDirectiveClass:
1228     case Stmt::OMPTeamsDistributeDirectiveClass:
1229     case Stmt::OMPTeamsDistributeSimdDirectiveClass:
1230     case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
1231     case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
1232     case Stmt::OMPTargetTeamsDirectiveClass:
1233     case Stmt::OMPTargetTeamsDistributeDirectiveClass:
1234     case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
1235     case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
1236     case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
1237     case Stmt::CapturedStmtClass: {
1238       const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1239       Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1240       break;
1241     }
1242 
1243     case Stmt::ParenExprClass:
1244       llvm_unreachable("ParenExprs already handled.");
1245     case Stmt::GenericSelectionExprClass:
1246       llvm_unreachable("GenericSelectionExprs already handled.");
1247     // Cases that should never be evaluated simply because they shouldn't
1248     // appear in the CFG.
1249     case Stmt::BreakStmtClass:
1250     case Stmt::CaseStmtClass:
1251     case Stmt::CompoundStmtClass:
1252     case Stmt::ContinueStmtClass:
1253     case Stmt::CXXForRangeStmtClass:
1254     case Stmt::DefaultStmtClass:
1255     case Stmt::DoStmtClass:
1256     case Stmt::ForStmtClass:
1257     case Stmt::GotoStmtClass:
1258     case Stmt::IfStmtClass:
1259     case Stmt::IndirectGotoStmtClass:
1260     case Stmt::LabelStmtClass:
1261     case Stmt::NoStmtClass:
1262     case Stmt::NullStmtClass:
1263     case Stmt::SwitchStmtClass:
1264     case Stmt::WhileStmtClass:
1265     case Expr::MSDependentExistsStmtClass:
1266       llvm_unreachable("Stmt should not be in analyzer evaluation loop");
1267 
1268     case Stmt::ObjCSubscriptRefExprClass:
1269     case Stmt::ObjCPropertyRefExprClass:
1270       llvm_unreachable("These are handled by PseudoObjectExpr");
1271 
1272     case Stmt::GNUNullExprClass: {
1273       // GNU __null is a pointer-width integer, not an actual pointer.
1274       ProgramStateRef state = Pred->getState();
1275       state = state->BindExpr(S, Pred->getLocationContext(),
1276                               svalBuilder.makeIntValWithPtrWidth(0, false));
1277       Bldr.generateNode(S, Pred, state);
1278       break;
1279     }
1280 
1281     case Stmt::ObjCAtSynchronizedStmtClass:
1282       Bldr.takeNodes(Pred);
1283       VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
1284       Bldr.addNodes(Dst);
1285       break;
1286 
1287     case Expr::ConstantExprClass:
1288     case Stmt::ExprWithCleanupsClass:
1289       // Handled due to fully linearised CFG.
1290       break;
1291 
1292     case Stmt::CXXBindTemporaryExprClass: {
1293       Bldr.takeNodes(Pred);
1294       ExplodedNodeSet PreVisit;
1295       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1296       ExplodedNodeSet Next;
1297       VisitCXXBindTemporaryExpr(cast<CXXBindTemporaryExpr>(S), PreVisit, Next);
1298       getCheckerManager().runCheckersForPostStmt(Dst, Next, S, *this);
1299       Bldr.addNodes(Dst);
1300       break;
1301     }
1302 
1303     // Cases not handled yet; but will handle some day.
1304     case Stmt::DesignatedInitExprClass:
1305     case Stmt::DesignatedInitUpdateExprClass:
1306     case Stmt::ArrayInitLoopExprClass:
1307     case Stmt::ArrayInitIndexExprClass:
1308     case Stmt::ExtVectorElementExprClass:
1309     case Stmt::ImaginaryLiteralClass:
1310     case Stmt::ObjCAtCatchStmtClass:
1311     case Stmt::ObjCAtFinallyStmtClass:
1312     case Stmt::ObjCAtTryStmtClass:
1313     case Stmt::ObjCAutoreleasePoolStmtClass:
1314     case Stmt::ObjCEncodeExprClass:
1315     case Stmt::ObjCIsaExprClass:
1316     case Stmt::ObjCProtocolExprClass:
1317     case Stmt::ObjCSelectorExprClass:
1318     case Stmt::ParenListExprClass:
1319     case Stmt::ShuffleVectorExprClass:
1320     case Stmt::ConvertVectorExprClass:
1321     case Stmt::VAArgExprClass:
1322     case Stmt::CUDAKernelCallExprClass:
1323     case Stmt::OpaqueValueExprClass:
1324     case Stmt::AsTypeExprClass:
1325       // Fall through.
1326 
1327     // Cases we intentionally don't evaluate, since they don't need
1328     // to be explicitly evaluated.
1329     case Stmt::PredefinedExprClass:
1330     case Stmt::AddrLabelExprClass:
1331     case Stmt::AttributedStmtClass:
1332     case Stmt::IntegerLiteralClass:
1333     case Stmt::FixedPointLiteralClass:
1334     case Stmt::CharacterLiteralClass:
1335     case Stmt::ImplicitValueInitExprClass:
1336     case Stmt::CXXScalarValueInitExprClass:
1337     case Stmt::CXXBoolLiteralExprClass:
1338     case Stmt::ObjCBoolLiteralExprClass:
1339     case Stmt::ObjCAvailabilityCheckExprClass:
1340     case Stmt::FloatingLiteralClass:
1341     case Stmt::NoInitExprClass:
1342     case Stmt::SizeOfPackExprClass:
1343     case Stmt::StringLiteralClass:
1344     case Stmt::ObjCStringLiteralClass:
1345     case Stmt::CXXPseudoDestructorExprClass:
1346     case Stmt::SubstNonTypeTemplateParmExprClass:
1347     case Stmt::CXXNullPtrLiteralExprClass:
1348     case Stmt::OMPArraySectionExprClass:
1349     case Stmt::TypeTraitExprClass: {
1350       Bldr.takeNodes(Pred);
1351       ExplodedNodeSet preVisit;
1352       getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1353       getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
1354       Bldr.addNodes(Dst);
1355       break;
1356     }
1357 
1358     case Stmt::CXXDefaultArgExprClass:
1359     case Stmt::CXXDefaultInitExprClass: {
1360       Bldr.takeNodes(Pred);
1361       ExplodedNodeSet PreVisit;
1362       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1363 
1364       ExplodedNodeSet Tmp;
1365       StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
1366 
1367       const Expr *ArgE;
1368       if (const auto *DefE = dyn_cast<CXXDefaultArgExpr>(S))
1369         ArgE = DefE->getExpr();
1370       else if (const auto *DefE = dyn_cast<CXXDefaultInitExpr>(S))
1371         ArgE = DefE->getExpr();
1372       else
1373         llvm_unreachable("unknown constant wrapper kind");
1374 
1375       bool IsTemporary = false;
1376       if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(ArgE)) {
1377         ArgE = MTE->GetTemporaryExpr();
1378         IsTemporary = true;
1379       }
1380 
1381       Optional<SVal> ConstantVal = svalBuilder.getConstantVal(ArgE);
1382       if (!ConstantVal)
1383         ConstantVal = UnknownVal();
1384 
1385       const LocationContext *LCtx = Pred->getLocationContext();
1386       for (const auto I : PreVisit) {
1387         ProgramStateRef State = I->getState();
1388         State = State->BindExpr(S, LCtx, *ConstantVal);
1389         if (IsTemporary)
1390           State = createTemporaryRegionIfNeeded(State, LCtx,
1391                                                 cast<Expr>(S),
1392                                                 cast<Expr>(S));
1393         Bldr2.generateNode(S, I, State);
1394       }
1395 
1396       getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1397       Bldr.addNodes(Dst);
1398       break;
1399     }
1400 
1401     // Cases we evaluate as opaque expressions, conjuring a symbol.
1402     case Stmt::CXXStdInitializerListExprClass:
1403     case Expr::ObjCArrayLiteralClass:
1404     case Expr::ObjCDictionaryLiteralClass:
1405     case Expr::ObjCBoxedExprClass: {
1406       Bldr.takeNodes(Pred);
1407 
1408       ExplodedNodeSet preVisit;
1409       getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
1410 
1411       ExplodedNodeSet Tmp;
1412       StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
1413 
1414       const auto *Ex = cast<Expr>(S);
1415       QualType resultType = Ex->getType();
1416 
1417       for (const auto N : preVisit) {
1418         const LocationContext *LCtx = N->getLocationContext();
1419         SVal result = svalBuilder.conjureSymbolVal(nullptr, Ex, LCtx,
1420                                                    resultType,
1421                                                    currBldrCtx->blockCount());
1422         ProgramStateRef State = N->getState()->BindExpr(Ex, LCtx, result);
1423 
1424         // Escape pointers passed into the list, unless it's an ObjC boxed
1425         // expression which is not a boxable C structure.
1426         if (!(isa<ObjCBoxedExpr>(Ex) &&
1427               !cast<ObjCBoxedExpr>(Ex)->getSubExpr()
1428                                       ->getType()->isRecordType()))
1429           for (auto Child : Ex->children()) {
1430             assert(Child);
1431             SVal Val = State->getSVal(Child, LCtx);
1432             State = escapeValue(State, Val, PSK_EscapeOther);
1433           }
1434 
1435         Bldr2.generateNode(S, N, State);
1436       }
1437 
1438       getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
1439       Bldr.addNodes(Dst);
1440       break;
1441     }
1442 
1443     case Stmt::ArraySubscriptExprClass:
1444       Bldr.takeNodes(Pred);
1445       VisitArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
1446       Bldr.addNodes(Dst);
1447       break;
1448 
1449     case Stmt::GCCAsmStmtClass:
1450       Bldr.takeNodes(Pred);
1451       VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
1452       Bldr.addNodes(Dst);
1453       break;
1454 
1455     case Stmt::MSAsmStmtClass:
1456       Bldr.takeNodes(Pred);
1457       VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
1458       Bldr.addNodes(Dst);
1459       break;
1460 
1461     case Stmt::BlockExprClass:
1462       Bldr.takeNodes(Pred);
1463       VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
1464       Bldr.addNodes(Dst);
1465       break;
1466 
1467     case Stmt::LambdaExprClass:
1468       if (AMgr.options.ShouldInlineLambdas) {
1469         Bldr.takeNodes(Pred);
1470         VisitLambdaExpr(cast<LambdaExpr>(S), Pred, Dst);
1471         Bldr.addNodes(Dst);
1472       } else {
1473         const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1474         Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1475       }
1476       break;
1477 
1478     case Stmt::BinaryOperatorClass: {
1479       const auto *B = cast<BinaryOperator>(S);
1480       if (B->isLogicalOp()) {
1481         Bldr.takeNodes(Pred);
1482         VisitLogicalExpr(B, Pred, Dst);
1483         Bldr.addNodes(Dst);
1484         break;
1485       }
1486       else if (B->getOpcode() == BO_Comma) {
1487         ProgramStateRef state = Pred->getState();
1488         Bldr.generateNode(B, Pred,
1489                           state->BindExpr(B, Pred->getLocationContext(),
1490                                           state->getSVal(B->getRHS(),
1491                                                   Pred->getLocationContext())));
1492         break;
1493       }
1494 
1495       Bldr.takeNodes(Pred);
1496 
1497       if (AMgr.options.ShouldEagerlyAssume &&
1498           (B->isRelationalOp() || B->isEqualityOp())) {
1499         ExplodedNodeSet Tmp;
1500         VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
1501         evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
1502       }
1503       else
1504         VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1505 
1506       Bldr.addNodes(Dst);
1507       break;
1508     }
1509 
1510     case Stmt::CXXOperatorCallExprClass: {
1511       const auto *OCE = cast<CXXOperatorCallExpr>(S);
1512 
1513       // For instance method operators, make sure the 'this' argument has a
1514       // valid region.
1515       const Decl *Callee = OCE->getCalleeDecl();
1516       if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
1517         if (MD->isInstance()) {
1518           ProgramStateRef State = Pred->getState();
1519           const LocationContext *LCtx = Pred->getLocationContext();
1520           ProgramStateRef NewState =
1521             createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
1522           if (NewState != State) {
1523             Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/nullptr,
1524                                      ProgramPoint::PreStmtKind);
1525             // Did we cache out?
1526             if (!Pred)
1527               break;
1528           }
1529         }
1530       }
1531       // FALLTHROUGH
1532       LLVM_FALLTHROUGH;
1533     }
1534 
1535     case Stmt::CallExprClass:
1536     case Stmt::CXXMemberCallExprClass:
1537     case Stmt::UserDefinedLiteralClass:
1538       Bldr.takeNodes(Pred);
1539       VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
1540       Bldr.addNodes(Dst);
1541       break;
1542 
1543     case Stmt::CXXCatchStmtClass:
1544       Bldr.takeNodes(Pred);
1545       VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
1546       Bldr.addNodes(Dst);
1547       break;
1548 
1549     case Stmt::CXXTemporaryObjectExprClass:
1550     case Stmt::CXXConstructExprClass:
1551       Bldr.takeNodes(Pred);
1552       VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
1553       Bldr.addNodes(Dst);
1554       break;
1555 
1556     case Stmt::CXXNewExprClass: {
1557       Bldr.takeNodes(Pred);
1558 
1559       ExplodedNodeSet PreVisit;
1560       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1561 
1562       ExplodedNodeSet PostVisit;
1563       for (const auto i : PreVisit)
1564         VisitCXXNewExpr(cast<CXXNewExpr>(S), i, PostVisit);
1565 
1566       getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1567       Bldr.addNodes(Dst);
1568       break;
1569     }
1570 
1571     case Stmt::CXXDeleteExprClass: {
1572       Bldr.takeNodes(Pred);
1573       ExplodedNodeSet PreVisit;
1574       const auto *CDE = cast<CXXDeleteExpr>(S);
1575       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1576 
1577       for (const auto i : PreVisit)
1578         VisitCXXDeleteExpr(CDE, i, Dst);
1579 
1580       Bldr.addNodes(Dst);
1581       break;
1582     }
1583       // FIXME: ChooseExpr is really a constant.  We need to fix
1584       //        the CFG do not model them as explicit control-flow.
1585 
1586     case Stmt::ChooseExprClass: { // __builtin_choose_expr
1587       Bldr.takeNodes(Pred);
1588       const auto *C = cast<ChooseExpr>(S);
1589       VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
1590       Bldr.addNodes(Dst);
1591       break;
1592     }
1593 
1594     case Stmt::CompoundAssignOperatorClass:
1595       Bldr.takeNodes(Pred);
1596       VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
1597       Bldr.addNodes(Dst);
1598       break;
1599 
1600     case Stmt::CompoundLiteralExprClass:
1601       Bldr.takeNodes(Pred);
1602       VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
1603       Bldr.addNodes(Dst);
1604       break;
1605 
1606     case Stmt::BinaryConditionalOperatorClass:
1607     case Stmt::ConditionalOperatorClass: { // '?' operator
1608       Bldr.takeNodes(Pred);
1609       const auto *C = cast<AbstractConditionalOperator>(S);
1610       VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
1611       Bldr.addNodes(Dst);
1612       break;
1613     }
1614 
1615     case Stmt::CXXThisExprClass:
1616       Bldr.takeNodes(Pred);
1617       VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
1618       Bldr.addNodes(Dst);
1619       break;
1620 
1621     case Stmt::DeclRefExprClass: {
1622       Bldr.takeNodes(Pred);
1623       const auto *DE = cast<DeclRefExpr>(S);
1624       VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
1625       Bldr.addNodes(Dst);
1626       break;
1627     }
1628 
1629     case Stmt::DeclStmtClass:
1630       Bldr.takeNodes(Pred);
1631       VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
1632       Bldr.addNodes(Dst);
1633       break;
1634 
1635     case Stmt::ImplicitCastExprClass:
1636     case Stmt::CStyleCastExprClass:
1637     case Stmt::CXXStaticCastExprClass:
1638     case Stmt::CXXDynamicCastExprClass:
1639     case Stmt::CXXReinterpretCastExprClass:
1640     case Stmt::CXXConstCastExprClass:
1641     case Stmt::CXXFunctionalCastExprClass:
1642     case Stmt::ObjCBridgedCastExprClass: {
1643       Bldr.takeNodes(Pred);
1644       const auto *C = cast<CastExpr>(S);
1645       ExplodedNodeSet dstExpr;
1646       VisitCast(C, C->getSubExpr(), Pred, dstExpr);
1647 
1648       // Handle the postvisit checks.
1649       getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
1650       Bldr.addNodes(Dst);
1651       break;
1652     }
1653 
1654     case Expr::MaterializeTemporaryExprClass: {
1655       Bldr.takeNodes(Pred);
1656       const auto *MTE = cast<MaterializeTemporaryExpr>(S);
1657       ExplodedNodeSet dstPrevisit;
1658       getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, MTE, *this);
1659       ExplodedNodeSet dstExpr;
1660       for (const auto i : dstPrevisit)
1661         CreateCXXTemporaryObject(MTE, i, dstExpr);
1662       getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, MTE, *this);
1663       Bldr.addNodes(Dst);
1664       break;
1665     }
1666 
1667     case Stmt::InitListExprClass:
1668       Bldr.takeNodes(Pred);
1669       VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
1670       Bldr.addNodes(Dst);
1671       break;
1672 
1673     case Stmt::MemberExprClass:
1674       Bldr.takeNodes(Pred);
1675       VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
1676       Bldr.addNodes(Dst);
1677       break;
1678 
1679     case Stmt::AtomicExprClass:
1680       Bldr.takeNodes(Pred);
1681       VisitAtomicExpr(cast<AtomicExpr>(S), Pred, Dst);
1682       Bldr.addNodes(Dst);
1683       break;
1684 
1685     case Stmt::ObjCIvarRefExprClass:
1686       Bldr.takeNodes(Pred);
1687       VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
1688       Bldr.addNodes(Dst);
1689       break;
1690 
1691     case Stmt::ObjCForCollectionStmtClass:
1692       Bldr.takeNodes(Pred);
1693       VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
1694       Bldr.addNodes(Dst);
1695       break;
1696 
1697     case Stmt::ObjCMessageExprClass:
1698       Bldr.takeNodes(Pred);
1699       VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
1700       Bldr.addNodes(Dst);
1701       break;
1702 
1703     case Stmt::ObjCAtThrowStmtClass:
1704     case Stmt::CXXThrowExprClass:
1705       // FIXME: This is not complete.  We basically treat @throw as
1706       // an abort.
1707       Bldr.generateSink(S, Pred, Pred->getState());
1708       break;
1709 
1710     case Stmt::ReturnStmtClass:
1711       Bldr.takeNodes(Pred);
1712       VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
1713       Bldr.addNodes(Dst);
1714       break;
1715 
1716     case Stmt::OffsetOfExprClass: {
1717       Bldr.takeNodes(Pred);
1718       ExplodedNodeSet PreVisit;
1719       getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
1720 
1721       ExplodedNodeSet PostVisit;
1722       for (const auto Node : PreVisit)
1723         VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Node, PostVisit);
1724 
1725       getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
1726       Bldr.addNodes(Dst);
1727       break;
1728     }
1729 
1730     case Stmt::UnaryExprOrTypeTraitExprClass:
1731       Bldr.takeNodes(Pred);
1732       VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
1733                                     Pred, Dst);
1734       Bldr.addNodes(Dst);
1735       break;
1736 
1737     case Stmt::StmtExprClass: {
1738       const auto *SE = cast<StmtExpr>(S);
1739 
1740       if (SE->getSubStmt()->body_empty()) {
1741         // Empty statement expression.
1742         assert(SE->getType() == getContext().VoidTy
1743                && "Empty statement expression must have void type.");
1744         break;
1745       }
1746 
1747       if (const auto *LastExpr =
1748               dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
1749         ProgramStateRef state = Pred->getState();
1750         Bldr.generateNode(SE, Pred,
1751                           state->BindExpr(SE, Pred->getLocationContext(),
1752                                           state->getSVal(LastExpr,
1753                                                   Pred->getLocationContext())));
1754       }
1755       break;
1756     }
1757 
1758     case Stmt::UnaryOperatorClass: {
1759       Bldr.takeNodes(Pred);
1760       const auto *U = cast<UnaryOperator>(S);
1761       if (AMgr.options.ShouldEagerlyAssume && (U->getOpcode() == UO_LNot)) {
1762         ExplodedNodeSet Tmp;
1763         VisitUnaryOperator(U, Pred, Tmp);
1764         evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
1765       }
1766       else
1767         VisitUnaryOperator(U, Pred, Dst);
1768       Bldr.addNodes(Dst);
1769       break;
1770     }
1771 
1772     case Stmt::PseudoObjectExprClass: {
1773       Bldr.takeNodes(Pred);
1774       ProgramStateRef state = Pred->getState();
1775       const auto *PE = cast<PseudoObjectExpr>(S);
1776       if (const Expr *Result = PE->getResultExpr()) {
1777         SVal V = state->getSVal(Result, Pred->getLocationContext());
1778         Bldr.generateNode(S, Pred,
1779                           state->BindExpr(S, Pred->getLocationContext(), V));
1780       }
1781       else
1782         Bldr.generateNode(S, Pred,
1783                           state->BindExpr(S, Pred->getLocationContext(),
1784                                                    UnknownVal()));
1785 
1786       Bldr.addNodes(Dst);
1787       break;
1788     }
1789   }
1790 }
1791 
1792 bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
1793                                        const LocationContext *CalleeLC) {
1794   const StackFrameContext *CalleeSF = CalleeLC->getStackFrame();
1795   const StackFrameContext *CallerSF = CalleeSF->getParent()->getStackFrame();
1796   assert(CalleeSF && CallerSF);
1797   ExplodedNode *BeforeProcessingCall = nullptr;
1798   const Stmt *CE = CalleeSF->getCallSite();
1799 
1800   // Find the first node before we started processing the call expression.
1801   while (N) {
1802     ProgramPoint L = N->getLocation();
1803     BeforeProcessingCall = N;
1804     N = N->pred_empty() ? nullptr : *(N->pred_begin());
1805 
1806     // Skip the nodes corresponding to the inlined code.
1807     if (L.getStackFrame() != CallerSF)
1808       continue;
1809     // We reached the caller. Find the node right before we started
1810     // processing the call.
1811     if (L.isPurgeKind())
1812       continue;
1813     if (L.getAs<PreImplicitCall>())
1814       continue;
1815     if (L.getAs<CallEnter>())
1816       continue;
1817     if (Optional<StmtPoint> SP = L.getAs<StmtPoint>())
1818       if (SP->getStmt() == CE)
1819         continue;
1820     break;
1821   }
1822 
1823   if (!BeforeProcessingCall)
1824     return false;
1825 
1826   // TODO: Clean up the unneeded nodes.
1827 
1828   // Build an Epsilon node from which we will restart the analyzes.
1829   // Note that CE is permitted to be NULL!
1830   ProgramPoint NewNodeLoc =
1831                EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
1832   // Add the special flag to GDM to signal retrying with no inlining.
1833   // Note, changing the state ensures that we are not going to cache out.
1834   ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
1835   NewNodeState =
1836     NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
1837 
1838   // Make the new node a successor of BeforeProcessingCall.
1839   bool IsNew = false;
1840   ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
1841   // We cached out at this point. Caching out is common due to us backtracking
1842   // from the inlined function, which might spawn several paths.
1843   if (!IsNew)
1844     return true;
1845 
1846   NewNode->addPredecessor(BeforeProcessingCall, G);
1847 
1848   // Add the new node to the work list.
1849   Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
1850                                   CalleeSF->getIndex());
1851   NumTimesRetriedWithoutInlining++;
1852   return true;
1853 }
1854 
1855 /// Block entrance.  (Update counters).
1856 void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
1857                                          NodeBuilderWithSinks &nodeBuilder,
1858                                          ExplodedNode *Pred) {
1859   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
1860   // If we reach a loop which has a known bound (and meets
1861   // other constraints) then consider completely unrolling it.
1862   if(AMgr.options.ShouldUnrollLoops) {
1863     unsigned maxBlockVisitOnPath = AMgr.options.maxBlockVisitOnPath;
1864     const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
1865     if (Term) {
1866       ProgramStateRef NewState = updateLoopStack(Term, AMgr.getASTContext(),
1867                                                  Pred, maxBlockVisitOnPath);
1868       if (NewState != Pred->getState()) {
1869         ExplodedNode *UpdatedNode = nodeBuilder.generateNode(NewState, Pred);
1870         if (!UpdatedNode)
1871           return;
1872         Pred = UpdatedNode;
1873       }
1874     }
1875     // Is we are inside an unrolled loop then no need the check the counters.
1876     if(isUnrolledState(Pred->getState()))
1877       return;
1878   }
1879 
1880   // If this block is terminated by a loop and it has already been visited the
1881   // maximum number of times, widen the loop.
1882   unsigned int BlockCount = nodeBuilder.getContext().blockCount();
1883   if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
1884       AMgr.options.ShouldWidenLoops) {
1885     const Stmt *Term = nodeBuilder.getContext().getBlock()->getTerminator();
1886     if (!(Term &&
1887           (isa<ForStmt>(Term) || isa<WhileStmt>(Term) || isa<DoStmt>(Term))))
1888       return;
1889     // Widen.
1890     const LocationContext *LCtx = Pred->getLocationContext();
1891     ProgramStateRef WidenedState =
1892         getWidenedLoopState(Pred->getState(), LCtx, BlockCount, Term);
1893     nodeBuilder.generateNode(WidenedState, Pred);
1894     return;
1895   }
1896 
1897   // FIXME: Refactor this into a checker.
1898   if (BlockCount >= AMgr.options.maxBlockVisitOnPath) {
1899     static SimpleProgramPointTag tag(TagProviderName, "Block count exceeded");
1900     const ExplodedNode *Sink =
1901                    nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
1902 
1903     // Check if we stopped at the top level function or not.
1904     // Root node should have the location context of the top most function.
1905     const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
1906     const LocationContext *CalleeSF = CalleeLC->getStackFrame();
1907     const LocationContext *RootLC =
1908                         (*G.roots_begin())->getLocation().getLocationContext();
1909     if (RootLC->getStackFrame() != CalleeSF) {
1910       Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
1911 
1912       // Re-run the call evaluation without inlining it, by storing the
1913       // no-inlining policy in the state and enqueuing the new work item on
1914       // the list. Replay should almost never fail. Use the stats to catch it
1915       // if it does.
1916       if ((!AMgr.options.NoRetryExhausted &&
1917            replayWithoutInlining(Pred, CalleeLC)))
1918         return;
1919       NumMaxBlockCountReachedInInlined++;
1920     } else
1921       NumMaxBlockCountReached++;
1922 
1923     // Make sink nodes as exhausted(for stats) only if retry failed.
1924     Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
1925   }
1926 }
1927 
1928 //===----------------------------------------------------------------------===//
1929 // Branch processing.
1930 //===----------------------------------------------------------------------===//
1931 
1932 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
1933 /// to try to recover some path-sensitivity for casts of symbolic
1934 /// integers that promote their values (which are currently not tracked well).
1935 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
1936 //  cast(s) did was sign-extend the original value.
1937 static SVal RecoverCastedSymbol(ProgramStateRef state,
1938                                 const Stmt *Condition,
1939                                 const LocationContext *LCtx,
1940                                 ASTContext &Ctx) {
1941 
1942   const auto *Ex = dyn_cast<Expr>(Condition);
1943   if (!Ex)
1944     return UnknownVal();
1945 
1946   uint64_t bits = 0;
1947   bool bitsInit = false;
1948 
1949   while (const auto *CE = dyn_cast<CastExpr>(Ex)) {
1950     QualType T = CE->getType();
1951 
1952     if (!T->isIntegralOrEnumerationType())
1953       return UnknownVal();
1954 
1955     uint64_t newBits = Ctx.getTypeSize(T);
1956     if (!bitsInit || newBits < bits) {
1957       bitsInit = true;
1958       bits = newBits;
1959     }
1960 
1961     Ex = CE->getSubExpr();
1962   }
1963 
1964   // We reached a non-cast.  Is it a symbolic value?
1965   QualType T = Ex->getType();
1966 
1967   if (!bitsInit || !T->isIntegralOrEnumerationType() ||
1968       Ctx.getTypeSize(T) > bits)
1969     return UnknownVal();
1970 
1971   return state->getSVal(Ex, LCtx);
1972 }
1973 
1974 #ifndef NDEBUG
1975 static const Stmt *getRightmostLeaf(const Stmt *Condition) {
1976   while (Condition) {
1977     const auto *BO = dyn_cast<BinaryOperator>(Condition);
1978     if (!BO || !BO->isLogicalOp()) {
1979       return Condition;
1980     }
1981     Condition = BO->getRHS()->IgnoreParens();
1982   }
1983   return nullptr;
1984 }
1985 #endif
1986 
1987 // Returns the condition the branch at the end of 'B' depends on and whose value
1988 // has been evaluated within 'B'.
1989 // In most cases, the terminator condition of 'B' will be evaluated fully in
1990 // the last statement of 'B'; in those cases, the resolved condition is the
1991 // given 'Condition'.
1992 // If the condition of the branch is a logical binary operator tree, the CFG is
1993 // optimized: in that case, we know that the expression formed by all but the
1994 // rightmost leaf of the logical binary operator tree must be true, and thus
1995 // the branch condition is at this point equivalent to the truth value of that
1996 // rightmost leaf; the CFG block thus only evaluates this rightmost leaf
1997 // expression in its final statement. As the full condition in that case was
1998 // not evaluated, and is thus not in the SVal cache, we need to use that leaf
1999 // expression to evaluate the truth value of the condition in the current state
2000 // space.
2001 static const Stmt *ResolveCondition(const Stmt *Condition,
2002                                     const CFGBlock *B) {
2003   if (const auto *Ex = dyn_cast<Expr>(Condition))
2004     Condition = Ex->IgnoreParens();
2005 
2006   const auto *BO = dyn_cast<BinaryOperator>(Condition);
2007   if (!BO || !BO->isLogicalOp())
2008     return Condition;
2009 
2010   assert(!B->getTerminator().isTemporaryDtorsBranch() &&
2011          "Temporary destructor branches handled by processBindTemporary.");
2012 
2013   // For logical operations, we still have the case where some branches
2014   // use the traditional "merge" approach and others sink the branch
2015   // directly into the basic blocks representing the logical operation.
2016   // We need to distinguish between those two cases here.
2017 
2018   // The invariants are still shifting, but it is possible that the
2019   // last element in a CFGBlock is not a CFGStmt.  Look for the last
2020   // CFGStmt as the value of the condition.
2021   CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
2022   for (; I != E; ++I) {
2023     CFGElement Elem = *I;
2024     Optional<CFGStmt> CS = Elem.getAs<CFGStmt>();
2025     if (!CS)
2026       continue;
2027     const Stmt *LastStmt = CS->getStmt();
2028     assert(LastStmt == Condition || LastStmt == getRightmostLeaf(Condition));
2029     return LastStmt;
2030   }
2031   llvm_unreachable("could not resolve condition");
2032 }
2033 
2034 void ExprEngine::processBranch(const Stmt *Condition,
2035                                NodeBuilderContext& BldCtx,
2036                                ExplodedNode *Pred,
2037                                ExplodedNodeSet &Dst,
2038                                const CFGBlock *DstT,
2039                                const CFGBlock *DstF) {
2040   assert((!Condition || !isa<CXXBindTemporaryExpr>(Condition)) &&
2041          "CXXBindTemporaryExprs are handled by processBindTemporary.");
2042   const LocationContext *LCtx = Pred->getLocationContext();
2043   PrettyStackTraceLocationContext StackCrashInfo(LCtx);
2044   currBldrCtx = &BldCtx;
2045 
2046   // Check for NULL conditions; e.g. "for(;;)"
2047   if (!Condition) {
2048     BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
2049     NullCondBldr.markInfeasible(false);
2050     NullCondBldr.generateNode(Pred->getState(), true, Pred);
2051     return;
2052   }
2053 
2054   if (const auto *Ex = dyn_cast<Expr>(Condition))
2055     Condition = Ex->IgnoreParens();
2056 
2057   Condition = ResolveCondition(Condition, BldCtx.getBlock());
2058   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
2059                                 Condition->getBeginLoc(),
2060                                 "Error evaluating branch");
2061 
2062   ExplodedNodeSet CheckersOutSet;
2063   getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
2064                                                     Pred, *this);
2065   // We generated only sinks.
2066   if (CheckersOutSet.empty())
2067     return;
2068 
2069   BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
2070   for (const auto PredI : CheckersOutSet) {
2071     if (PredI->isSink())
2072       continue;
2073 
2074     ProgramStateRef PrevState = PredI->getState();
2075     SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
2076 
2077     if (X.isUnknownOrUndef()) {
2078       // Give it a chance to recover from unknown.
2079       if (const auto *Ex = dyn_cast<Expr>(Condition)) {
2080         if (Ex->getType()->isIntegralOrEnumerationType()) {
2081           // Try to recover some path-sensitivity.  Right now casts of symbolic
2082           // integers that promote their values are currently not tracked well.
2083           // If 'Condition' is such an expression, try and recover the
2084           // underlying value and use that instead.
2085           SVal recovered = RecoverCastedSymbol(PrevState, Condition,
2086                                                PredI->getLocationContext(),
2087                                                getContext());
2088 
2089           if (!recovered.isUnknown()) {
2090             X = recovered;
2091           }
2092         }
2093       }
2094     }
2095 
2096     // If the condition is still unknown, give up.
2097     if (X.isUnknownOrUndef()) {
2098       builder.generateNode(PrevState, true, PredI);
2099       builder.generateNode(PrevState, false, PredI);
2100       continue;
2101     }
2102 
2103     DefinedSVal V = X.castAs<DefinedSVal>();
2104 
2105     ProgramStateRef StTrue, StFalse;
2106     std::tie(StTrue, StFalse) = PrevState->assume(V);
2107 
2108     // Process the true branch.
2109     if (builder.isFeasible(true)) {
2110       if (StTrue)
2111         builder.generateNode(StTrue, true, PredI);
2112       else
2113         builder.markInfeasible(true);
2114     }
2115 
2116     // Process the false branch.
2117     if (builder.isFeasible(false)) {
2118       if (StFalse)
2119         builder.generateNode(StFalse, false, PredI);
2120       else
2121         builder.markInfeasible(false);
2122     }
2123   }
2124   currBldrCtx = nullptr;
2125 }
2126 
2127 /// The GDM component containing the set of global variables which have been
2128 /// previously initialized with explicit initializers.
2129 REGISTER_TRAIT_WITH_PROGRAMSTATE(InitializedGlobalsSet,
2130                                  llvm::ImmutableSet<const VarDecl *>)
2131 
2132 void ExprEngine::processStaticInitializer(const DeclStmt *DS,
2133                                           NodeBuilderContext &BuilderCtx,
2134                                           ExplodedNode *Pred,
2135                                           ExplodedNodeSet &Dst,
2136                                           const CFGBlock *DstT,
2137                                           const CFGBlock *DstF) {
2138   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
2139   currBldrCtx = &BuilderCtx;
2140 
2141   const auto *VD = cast<VarDecl>(DS->getSingleDecl());
2142   ProgramStateRef state = Pred->getState();
2143   bool initHasRun = state->contains<InitializedGlobalsSet>(VD);
2144   BranchNodeBuilder builder(Pred, Dst, BuilderCtx, DstT, DstF);
2145 
2146   if (!initHasRun) {
2147     state = state->add<InitializedGlobalsSet>(VD);
2148   }
2149 
2150   builder.generateNode(state, initHasRun, Pred);
2151   builder.markInfeasible(!initHasRun);
2152 
2153   currBldrCtx = nullptr;
2154 }
2155 
2156 /// processIndirectGoto - Called by CoreEngine.  Used to generate successor
2157 ///  nodes by processing the 'effects' of a computed goto jump.
2158 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
2159   ProgramStateRef state = builder.getState();
2160   SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
2161 
2162   // Three possibilities:
2163   //
2164   //   (1) We know the computed label.
2165   //   (2) The label is NULL (or some other constant), or Undefined.
2166   //   (3) We have no clue about the label.  Dispatch to all targets.
2167   //
2168 
2169   using iterator = IndirectGotoNodeBuilder::iterator;
2170 
2171   if (Optional<loc::GotoLabel> LV = V.getAs<loc::GotoLabel>()) {
2172     const LabelDecl *L = LV->getLabel();
2173 
2174     for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
2175       if (I.getLabel() == L) {
2176         builder.generateNode(I, state);
2177         return;
2178       }
2179     }
2180 
2181     llvm_unreachable("No block with label.");
2182   }
2183 
2184   if (V.getAs<loc::ConcreteInt>() || V.getAs<UndefinedVal>()) {
2185     // Dispatch to the first target and mark it as a sink.
2186     //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
2187     // FIXME: add checker visit.
2188     //    UndefBranches.insert(N);
2189     return;
2190   }
2191 
2192   // This is really a catch-all.  We don't support symbolics yet.
2193   // FIXME: Implement dispatch for symbolic pointers.
2194 
2195   for (iterator I = builder.begin(), E = builder.end(); I != E; ++I)
2196     builder.generateNode(I, state);
2197 }
2198 
2199 void ExprEngine::processBeginOfFunction(NodeBuilderContext &BC,
2200                                         ExplodedNode *Pred,
2201                                         ExplodedNodeSet &Dst,
2202                                         const BlockEdge &L) {
2203   SaveAndRestore<const NodeBuilderContext *> NodeContextRAII(currBldrCtx, &BC);
2204   getCheckerManager().runCheckersForBeginFunction(Dst, L, Pred, *this);
2205 }
2206 
2207 /// ProcessEndPath - Called by CoreEngine.  Used to generate end-of-path
2208 ///  nodes when the control reaches the end of a function.
2209 void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
2210                                       ExplodedNode *Pred,
2211                                       const ReturnStmt *RS) {
2212   ProgramStateRef State = Pred->getState();
2213 
2214   if (!Pred->getStackFrame()->inTopFrame())
2215     State = finishArgumentConstruction(
2216         State, *getStateManager().getCallEventManager().getCaller(
2217                    Pred->getStackFrame(), Pred->getState()));
2218 
2219   // FIXME: We currently cannot assert that temporaries are clear, because
2220   // lifetime extended temporaries are not always modelled correctly. In some
2221   // cases when we materialize the temporary, we do
2222   // createTemporaryRegionIfNeeded(), and the region changes, and also the
2223   // respective destructor becomes automatic from temporary. So for now clean up
2224   // the state manually before asserting. Ideally, this braced block of code
2225   // should go away.
2226   {
2227     const LocationContext *FromLC = Pred->getLocationContext();
2228     const LocationContext *ToLC = FromLC->getStackFrame()->getParent();
2229     const LocationContext *LC = FromLC;
2230     while (LC != ToLC) {
2231       assert(LC && "ToLC must be a parent of FromLC!");
2232       for (auto I : State->get<ObjectsUnderConstruction>())
2233         if (I.first.getLocationContext() == LC) {
2234           // The comment above only pardons us for not cleaning up a
2235           // temporary destructor. If any other statements are found here,
2236           // it must be a separate problem.
2237           assert(I.first.getItem().getKind() ==
2238                      ConstructionContextItem::TemporaryDestructorKind ||
2239                  I.first.getItem().getKind() ==
2240                      ConstructionContextItem::ElidedDestructorKind);
2241           State = State->remove<ObjectsUnderConstruction>(I.first);
2242         }
2243       LC = LC->getParent();
2244     }
2245   }
2246 
2247   // Perform the transition with cleanups.
2248   if (State != Pred->getState()) {
2249     ExplodedNodeSet PostCleanup;
2250     NodeBuilder Bldr(Pred, PostCleanup, BC);
2251     Pred = Bldr.generateNode(Pred->getLocation(), State, Pred);
2252     if (!Pred) {
2253       // The node with clean temporaries already exists. We might have reached
2254       // it on a path on which we initialize different temporaries.
2255       return;
2256     }
2257   }
2258 
2259   assert(areAllObjectsFullyConstructed(Pred->getState(),
2260                                        Pred->getLocationContext(),
2261                                        Pred->getStackFrame()->getParent()));
2262 
2263   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
2264   StateMgr.EndPath(Pred->getState());
2265 
2266   ExplodedNodeSet Dst;
2267   if (Pred->getLocationContext()->inTopFrame()) {
2268     // Remove dead symbols.
2269     ExplodedNodeSet AfterRemovedDead;
2270     removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
2271 
2272     // Notify checkers.
2273     for (const auto I : AfterRemovedDead)
2274       getCheckerManager().runCheckersForEndFunction(BC, Dst, I, *this, RS);
2275   } else {
2276     getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this, RS);
2277   }
2278 
2279   Engine.enqueueEndOfFunction(Dst, RS);
2280 }
2281 
2282 /// ProcessSwitch - Called by CoreEngine.  Used to generate successor
2283 ///  nodes by processing the 'effects' of a switch statement.
2284 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
2285   using iterator = SwitchNodeBuilder::iterator;
2286 
2287   ProgramStateRef state = builder.getState();
2288   const Expr *CondE = builder.getCondition();
2289   SVal  CondV_untested = state->getSVal(CondE, builder.getLocationContext());
2290 
2291   if (CondV_untested.isUndef()) {
2292     //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
2293     // FIXME: add checker
2294     //UndefBranches.insert(N);
2295 
2296     return;
2297   }
2298   DefinedOrUnknownSVal CondV = CondV_untested.castAs<DefinedOrUnknownSVal>();
2299 
2300   ProgramStateRef DefaultSt = state;
2301 
2302   iterator I = builder.begin(), EI = builder.end();
2303   bool defaultIsFeasible = I == EI;
2304 
2305   for ( ; I != EI; ++I) {
2306     // Successor may be pruned out during CFG construction.
2307     if (!I.getBlock())
2308       continue;
2309 
2310     const CaseStmt *Case = I.getCase();
2311 
2312     // Evaluate the LHS of the case value.
2313     llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
2314     assert(V1.getBitWidth() == getContext().getIntWidth(CondE->getType()));
2315 
2316     // Get the RHS of the case, if it exists.
2317     llvm::APSInt V2;
2318     if (const Expr *E = Case->getRHS())
2319       V2 = E->EvaluateKnownConstInt(getContext());
2320     else
2321       V2 = V1;
2322 
2323     ProgramStateRef StateCase;
2324     if (Optional<NonLoc> NL = CondV.getAs<NonLoc>())
2325       std::tie(StateCase, DefaultSt) =
2326           DefaultSt->assumeInclusiveRange(*NL, V1, V2);
2327     else // UnknownVal
2328       StateCase = DefaultSt;
2329 
2330     if (StateCase)
2331       builder.generateCaseStmtNode(I, StateCase);
2332 
2333     // Now "assume" that the case doesn't match.  Add this state
2334     // to the default state (if it is feasible).
2335     if (DefaultSt)
2336       defaultIsFeasible = true;
2337     else {
2338       defaultIsFeasible = false;
2339       break;
2340     }
2341   }
2342 
2343   if (!defaultIsFeasible)
2344     return;
2345 
2346   // If we have switch(enum value), the default branch is not
2347   // feasible if all of the enum constants not covered by 'case:' statements
2348   // are not feasible values for the switch condition.
2349   //
2350   // Note that this isn't as accurate as it could be.  Even if there isn't
2351   // a case for a particular enum value as long as that enum value isn't
2352   // feasible then it shouldn't be considered for making 'default:' reachable.
2353   const SwitchStmt *SS = builder.getSwitch();
2354   const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
2355   if (CondExpr->getType()->getAs<EnumType>()) {
2356     if (SS->isAllEnumCasesCovered())
2357       return;
2358   }
2359 
2360   builder.generateDefaultCaseNode(DefaultSt);
2361 }
2362 
2363 //===----------------------------------------------------------------------===//
2364 // Transfer functions: Loads and stores.
2365 //===----------------------------------------------------------------------===//
2366 
2367 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
2368                                         ExplodedNode *Pred,
2369                                         ExplodedNodeSet &Dst) {
2370   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2371 
2372   ProgramStateRef state = Pred->getState();
2373   const LocationContext *LCtx = Pred->getLocationContext();
2374 
2375   if (const auto *VD = dyn_cast<VarDecl>(D)) {
2376     // C permits "extern void v", and if you cast the address to a valid type,
2377     // you can even do things with it. We simply pretend
2378     assert(Ex->isGLValue() || VD->getType()->isVoidType());
2379     const LocationContext *LocCtxt = Pred->getLocationContext();
2380     const Decl *D = LocCtxt->getDecl();
2381     const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D);
2382     const auto *DeclRefEx = dyn_cast<DeclRefExpr>(Ex);
2383     Optional<std::pair<SVal, QualType>> VInfo;
2384 
2385     if (AMgr.options.ShouldInlineLambdas && DeclRefEx &&
2386         DeclRefEx->refersToEnclosingVariableOrCapture() && MD &&
2387         MD->getParent()->isLambda()) {
2388       // Lookup the field of the lambda.
2389       const CXXRecordDecl *CXXRec = MD->getParent();
2390       llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
2391       FieldDecl *LambdaThisCaptureField;
2392       CXXRec->getCaptureFields(LambdaCaptureFields, LambdaThisCaptureField);
2393 
2394       // Sema follows a sequence of complex rules to determine whether the
2395       // variable should be captured.
2396       if (const FieldDecl *FD = LambdaCaptureFields[VD]) {
2397         Loc CXXThis =
2398             svalBuilder.getCXXThis(MD, LocCtxt->getStackFrame());
2399         SVal CXXThisVal = state->getSVal(CXXThis);
2400         VInfo = std::make_pair(state->getLValue(FD, CXXThisVal), FD->getType());
2401       }
2402     }
2403 
2404     if (!VInfo)
2405       VInfo = std::make_pair(state->getLValue(VD, LocCtxt), VD->getType());
2406 
2407     SVal V = VInfo->first;
2408     bool IsReference = VInfo->second->isReferenceType();
2409 
2410     // For references, the 'lvalue' is the pointer address stored in the
2411     // reference region.
2412     if (IsReference) {
2413       if (const MemRegion *R = V.getAsRegion())
2414         V = state->getSVal(R);
2415       else
2416         V = UnknownVal();
2417     }
2418 
2419     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2420                       ProgramPoint::PostLValueKind);
2421     return;
2422   }
2423   if (const auto *ED = dyn_cast<EnumConstantDecl>(D)) {
2424     assert(!Ex->isGLValue());
2425     SVal V = svalBuilder.makeIntVal(ED->getInitVal());
2426     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
2427     return;
2428   }
2429   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2430     SVal V = svalBuilder.getFunctionPointer(FD);
2431     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2432                       ProgramPoint::PostLValueKind);
2433     return;
2434   }
2435   if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
2436     // FIXME: Compute lvalue of field pointers-to-member.
2437     // Right now we just use a non-null void pointer, so that it gives proper
2438     // results in boolean contexts.
2439     // FIXME: Maybe delegate this to the surrounding operator&.
2440     // Note how this expression is lvalue, however pointer-to-member is NonLoc.
2441     SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
2442                                           currBldrCtx->blockCount());
2443     state = state->assume(V.castAs<DefinedOrUnknownSVal>(), true);
2444     Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), nullptr,
2445                       ProgramPoint::PostLValueKind);
2446     return;
2447   }
2448   if (isa<BindingDecl>(D)) {
2449     // FIXME: proper support for bound declarations.
2450     // For now, let's just prevent crashing.
2451     return;
2452   }
2453 
2454   llvm_unreachable("Support for this Decl not implemented.");
2455 }
2456 
2457 /// VisitArraySubscriptExpr - Transfer function for array accesses
2458 void ExprEngine::VisitArraySubscriptExpr(const ArraySubscriptExpr *A,
2459                                              ExplodedNode *Pred,
2460                                              ExplodedNodeSet &Dst){
2461   const Expr *Base = A->getBase()->IgnoreParens();
2462   const Expr *Idx  = A->getIdx()->IgnoreParens();
2463 
2464   ExplodedNodeSet CheckerPreStmt;
2465   getCheckerManager().runCheckersForPreStmt(CheckerPreStmt, Pred, A, *this);
2466 
2467   ExplodedNodeSet EvalSet;
2468   StmtNodeBuilder Bldr(CheckerPreStmt, EvalSet, *currBldrCtx);
2469 
2470   bool IsVectorType = A->getBase()->getType()->isVectorType();
2471 
2472   // The "like" case is for situations where C standard prohibits the type to
2473   // be an lvalue, e.g. taking the address of a subscript of an expression of
2474   // type "void *".
2475   bool IsGLValueLike = A->isGLValue() ||
2476     (A->getType().isCForbiddenLValueType() && !AMgr.getLangOpts().CPlusPlus);
2477 
2478   for (auto *Node : CheckerPreStmt) {
2479     const LocationContext *LCtx = Node->getLocationContext();
2480     ProgramStateRef state = Node->getState();
2481 
2482     if (IsGLValueLike) {
2483       QualType T = A->getType();
2484 
2485       // One of the forbidden LValue types! We still need to have sensible
2486       // symbolic locations to represent this stuff. Note that arithmetic on
2487       // void pointers is a GCC extension.
2488       if (T->isVoidType())
2489         T = getContext().CharTy;
2490 
2491       SVal V = state->getLValue(T,
2492                                 state->getSVal(Idx, LCtx),
2493                                 state->getSVal(Base, LCtx));
2494       Bldr.generateNode(A, Node, state->BindExpr(A, LCtx, V), nullptr,
2495           ProgramPoint::PostLValueKind);
2496     } else if (IsVectorType) {
2497       // FIXME: non-glvalue vector reads are not modelled.
2498       Bldr.generateNode(A, Node, state, nullptr);
2499     } else {
2500       llvm_unreachable("Array subscript should be an lValue when not \
2501 a vector and not a forbidden lvalue type");
2502     }
2503   }
2504 
2505   getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, A, *this);
2506 }
2507 
2508 /// VisitMemberExpr - Transfer function for member expressions.
2509 void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
2510                                  ExplodedNodeSet &Dst) {
2511   // FIXME: Prechecks eventually go in ::Visit().
2512   ExplodedNodeSet CheckedSet;
2513   getCheckerManager().runCheckersForPreStmt(CheckedSet, Pred, M, *this);
2514 
2515   ExplodedNodeSet EvalSet;
2516   ValueDecl *Member = M->getMemberDecl();
2517 
2518   // Handle static member variables and enum constants accessed via
2519   // member syntax.
2520   if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
2521     for (const auto I : CheckedSet)
2522       VisitCommonDeclRefExpr(M, Member, I, EvalSet);
2523   } else {
2524     StmtNodeBuilder Bldr(CheckedSet, EvalSet, *currBldrCtx);
2525     ExplodedNodeSet Tmp;
2526 
2527     for (const auto I : CheckedSet) {
2528       ProgramStateRef state = I->getState();
2529       const LocationContext *LCtx = I->getLocationContext();
2530       Expr *BaseExpr = M->getBase();
2531 
2532       // Handle C++ method calls.
2533       if (const auto *MD = dyn_cast<CXXMethodDecl>(Member)) {
2534         if (MD->isInstance())
2535           state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
2536 
2537         SVal MDVal = svalBuilder.getFunctionPointer(MD);
2538         state = state->BindExpr(M, LCtx, MDVal);
2539 
2540         Bldr.generateNode(M, I, state);
2541         continue;
2542       }
2543 
2544       // Handle regular struct fields / member variables.
2545       const SubRegion *MR = nullptr;
2546       state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr,
2547                                             /*Result=*/nullptr,
2548                                             /*OutRegionWithAdjustments=*/&MR);
2549       SVal baseExprVal =
2550           MR ? loc::MemRegionVal(MR) : state->getSVal(BaseExpr, LCtx);
2551 
2552       const auto *field = cast<FieldDecl>(Member);
2553       SVal L = state->getLValue(field, baseExprVal);
2554 
2555       if (M->isGLValue() || M->getType()->isArrayType()) {
2556         // We special-case rvalues of array type because the analyzer cannot
2557         // reason about them, since we expect all regions to be wrapped in Locs.
2558         // We instead treat these as lvalues and assume that they will decay to
2559         // pointers as soon as they are used.
2560         if (!M->isGLValue()) {
2561           assert(M->getType()->isArrayType());
2562           const auto *PE =
2563             dyn_cast<ImplicitCastExpr>(I->getParentMap().getParentIgnoreParens(M));
2564           if (!PE || PE->getCastKind() != CK_ArrayToPointerDecay) {
2565             llvm_unreachable("should always be wrapped in ArrayToPointerDecay");
2566           }
2567         }
2568 
2569         if (field->getType()->isReferenceType()) {
2570           if (const MemRegion *R = L.getAsRegion())
2571             L = state->getSVal(R);
2572           else
2573             L = UnknownVal();
2574         }
2575 
2576         Bldr.generateNode(M, I, state->BindExpr(M, LCtx, L), nullptr,
2577                           ProgramPoint::PostLValueKind);
2578       } else {
2579         Bldr.takeNodes(I);
2580         evalLoad(Tmp, M, M, I, state, L);
2581         Bldr.addNodes(Tmp);
2582       }
2583     }
2584   }
2585 
2586   getCheckerManager().runCheckersForPostStmt(Dst, EvalSet, M, *this);
2587 }
2588 
2589 void ExprEngine::VisitAtomicExpr(const AtomicExpr *AE, ExplodedNode *Pred,
2590                                  ExplodedNodeSet &Dst) {
2591   ExplodedNodeSet AfterPreSet;
2592   getCheckerManager().runCheckersForPreStmt(AfterPreSet, Pred, AE, *this);
2593 
2594   // For now, treat all the arguments to C11 atomics as escaping.
2595   // FIXME: Ideally we should model the behavior of the atomics precisely here.
2596 
2597   ExplodedNodeSet AfterInvalidateSet;
2598   StmtNodeBuilder Bldr(AfterPreSet, AfterInvalidateSet, *currBldrCtx);
2599 
2600   for (const auto I : AfterPreSet) {
2601     ProgramStateRef State = I->getState();
2602     const LocationContext *LCtx = I->getLocationContext();
2603 
2604     SmallVector<SVal, 8> ValuesToInvalidate;
2605     for (unsigned SI = 0, Count = AE->getNumSubExprs(); SI != Count; SI++) {
2606       const Expr *SubExpr = AE->getSubExprs()[SI];
2607       SVal SubExprVal = State->getSVal(SubExpr, LCtx);
2608       ValuesToInvalidate.push_back(SubExprVal);
2609     }
2610 
2611     State = State->invalidateRegions(ValuesToInvalidate, AE,
2612                                     currBldrCtx->blockCount(),
2613                                     LCtx,
2614                                     /*CausedByPointerEscape*/true,
2615                                     /*Symbols=*/nullptr);
2616 
2617     SVal ResultVal = UnknownVal();
2618     State = State->BindExpr(AE, LCtx, ResultVal);
2619     Bldr.generateNode(AE, I, State, nullptr,
2620                       ProgramPoint::PostStmtKind);
2621   }
2622 
2623   getCheckerManager().runCheckersForPostStmt(Dst, AfterInvalidateSet, AE, *this);
2624 }
2625 
2626 // A value escapes in four possible cases:
2627 // (1) We are binding to something that is not a memory region.
2628 // (2) We are binding to a MemRegion that does not have stack storage.
2629 // (3) We are binding to a top-level parameter region with a non-trivial
2630 //     destructor. We won't see the destructor during analysis, but it's there.
2631 // (4) We are binding to a MemRegion with stack storage that the store
2632 //     does not understand.
2633 ProgramStateRef
2634 ExprEngine::processPointerEscapedOnBind(ProgramStateRef State, SVal Loc,
2635                                         SVal Val, const LocationContext *LCtx) {
2636 
2637   // Cases (1) and (2).
2638   const MemRegion *MR = Loc.getAsRegion();
2639   if (!MR || !MR->hasStackStorage())
2640     return escapeValue(State, Val, PSK_EscapeOnBind);
2641 
2642   // Case (3).
2643   if (const auto *VR = dyn_cast<VarRegion>(MR->getBaseRegion()))
2644     if (VR->hasStackParametersStorage() && VR->getStackFrame()->inTopFrame())
2645       if (const auto *RD = VR->getValueType()->getAsCXXRecordDecl())
2646         if (!RD->hasTrivialDestructor())
2647           return escapeValue(State, Val, PSK_EscapeOnBind);
2648 
2649   // Case (4): in order to test that, generate a new state with the binding
2650   // added. If it is the same state, then it escapes (since the store cannot
2651   // represent the binding).
2652   // Do this only if we know that the store is not supposed to generate the
2653   // same state.
2654   SVal StoredVal = State->getSVal(MR);
2655   if (StoredVal != Val)
2656     if (State == (State->bindLoc(loc::MemRegionVal(MR), Val, LCtx)))
2657       return escapeValue(State, Val, PSK_EscapeOnBind);
2658 
2659   return State;
2660 }
2661 
2662 ProgramStateRef
2663 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
2664     const InvalidatedSymbols *Invalidated,
2665     ArrayRef<const MemRegion *> ExplicitRegions,
2666     const CallEvent *Call,
2667     RegionAndSymbolInvalidationTraits &ITraits) {
2668   if (!Invalidated || Invalidated->empty())
2669     return State;
2670 
2671   if (!Call)
2672     return getCheckerManager().runCheckersForPointerEscape(State,
2673                                                            *Invalidated,
2674                                                            nullptr,
2675                                                            PSK_EscapeOther,
2676                                                            &ITraits);
2677 
2678   // If the symbols were invalidated by a call, we want to find out which ones
2679   // were invalidated directly due to being arguments to the call.
2680   InvalidatedSymbols SymbolsDirectlyInvalidated;
2681   for (const auto I : ExplicitRegions) {
2682     if (const SymbolicRegion *R = I->StripCasts()->getAs<SymbolicRegion>())
2683       SymbolsDirectlyInvalidated.insert(R->getSymbol());
2684   }
2685 
2686   InvalidatedSymbols SymbolsIndirectlyInvalidated;
2687   for (const auto &sym : *Invalidated) {
2688     if (SymbolsDirectlyInvalidated.count(sym))
2689       continue;
2690     SymbolsIndirectlyInvalidated.insert(sym);
2691   }
2692 
2693   if (!SymbolsDirectlyInvalidated.empty())
2694     State = getCheckerManager().runCheckersForPointerEscape(State,
2695         SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
2696 
2697   // Notify about the symbols that get indirectly invalidated by the call.
2698   if (!SymbolsIndirectlyInvalidated.empty())
2699     State = getCheckerManager().runCheckersForPointerEscape(State,
2700         SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
2701 
2702   return State;
2703 }
2704 
2705 /// evalBind - Handle the semantics of binding a value to a specific location.
2706 ///  This method is used by evalStore and (soon) VisitDeclStmt, and others.
2707 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
2708                           ExplodedNode *Pred,
2709                           SVal location, SVal Val,
2710                           bool atDeclInit, const ProgramPoint *PP) {
2711   const LocationContext *LC = Pred->getLocationContext();
2712   PostStmt PS(StoreE, LC);
2713   if (!PP)
2714     PP = &PS;
2715 
2716   // Do a previsit of the bind.
2717   ExplodedNodeSet CheckedSet;
2718   getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
2719                                          StoreE, *this, *PP);
2720 
2721   StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
2722 
2723   // If the location is not a 'Loc', it will already be handled by
2724   // the checkers.  There is nothing left to do.
2725   if (!location.getAs<Loc>()) {
2726     const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
2727                                      /*tag*/nullptr);
2728     ProgramStateRef state = Pred->getState();
2729     state = processPointerEscapedOnBind(state, location, Val, LC);
2730     Bldr.generateNode(L, state, Pred);
2731     return;
2732   }
2733 
2734   for (const auto PredI : CheckedSet) {
2735     ProgramStateRef state = PredI->getState();
2736 
2737     state = processPointerEscapedOnBind(state, location, Val, LC);
2738 
2739     // When binding the value, pass on the hint that this is a initialization.
2740     // For initializations, we do not need to inform clients of region
2741     // changes.
2742     state = state->bindLoc(location.castAs<Loc>(),
2743                            Val, LC, /* notifyChanges = */ !atDeclInit);
2744 
2745     const MemRegion *LocReg = nullptr;
2746     if (Optional<loc::MemRegionVal> LocRegVal =
2747             location.getAs<loc::MemRegionVal>()) {
2748       LocReg = LocRegVal->getRegion();
2749     }
2750 
2751     const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
2752     Bldr.generateNode(L, state, PredI);
2753   }
2754 }
2755 
2756 /// evalStore - Handle the semantics of a store via an assignment.
2757 ///  @param Dst The node set to store generated state nodes
2758 ///  @param AssignE The assignment expression if the store happens in an
2759 ///         assignment.
2760 ///  @param LocationE The location expression that is stored to.
2761 ///  @param state The current simulation state
2762 ///  @param location The location to store the value
2763 ///  @param Val The value to be stored
2764 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
2765                              const Expr *LocationE,
2766                              ExplodedNode *Pred,
2767                              ProgramStateRef state, SVal location, SVal Val,
2768                              const ProgramPointTag *tag) {
2769   // Proceed with the store.  We use AssignE as the anchor for the PostStore
2770   // ProgramPoint if it is non-NULL, and LocationE otherwise.
2771   const Expr *StoreE = AssignE ? AssignE : LocationE;
2772 
2773   // Evaluate the location (checks for bad dereferences).
2774   ExplodedNodeSet Tmp;
2775   evalLocation(Tmp, AssignE, LocationE, Pred, state, location, false);
2776 
2777   if (Tmp.empty())
2778     return;
2779 
2780   if (location.isUndef())
2781     return;
2782 
2783   for (const auto I : Tmp)
2784     evalBind(Dst, StoreE, I, location, Val, false);
2785 }
2786 
2787 void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
2788                           const Expr *NodeEx,
2789                           const Expr *BoundEx,
2790                           ExplodedNode *Pred,
2791                           ProgramStateRef state,
2792                           SVal location,
2793                           const ProgramPointTag *tag,
2794                           QualType LoadTy) {
2795   assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
2796   assert(NodeEx);
2797   assert(BoundEx);
2798   // Evaluate the location (checks for bad dereferences).
2799   ExplodedNodeSet Tmp;
2800   evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, true);
2801   if (Tmp.empty())
2802     return;
2803 
2804   StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2805   if (location.isUndef())
2806     return;
2807 
2808   // Proceed with the load.
2809   for (const auto I : Tmp) {
2810     state = I->getState();
2811     const LocationContext *LCtx = I->getLocationContext();
2812 
2813     SVal V = UnknownVal();
2814     if (location.isValid()) {
2815       if (LoadTy.isNull())
2816         LoadTy = BoundEx->getType();
2817       V = state->getSVal(location.castAs<Loc>(), LoadTy);
2818     }
2819 
2820     Bldr.generateNode(NodeEx, I, state->BindExpr(BoundEx, LCtx, V), tag,
2821                       ProgramPoint::PostLoadKind);
2822   }
2823 }
2824 
2825 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2826                               const Stmt *NodeEx,
2827                               const Stmt *BoundEx,
2828                               ExplodedNode *Pred,
2829                               ProgramStateRef state,
2830                               SVal location,
2831                               bool isLoad) {
2832   StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2833   // Early checks for performance reason.
2834   if (location.isUnknown()) {
2835     return;
2836   }
2837 
2838   ExplodedNodeSet Src;
2839   BldrTop.takeNodes(Pred);
2840   StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2841   if (Pred->getState() != state) {
2842     // Associate this new state with an ExplodedNode.
2843     // FIXME: If I pass null tag, the graph is incorrect, e.g for
2844     //   int *p;
2845     //   p = 0;
2846     //   *p = 0xDEADBEEF;
2847     // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2848     // instead "int *p" is noted as
2849     // "Variable 'p' initialized to a null pointer value"
2850 
2851     static SimpleProgramPointTag tag(TagProviderName, "Location");
2852     Bldr.generateNode(NodeEx, Pred, state, &tag);
2853   }
2854   ExplodedNodeSet Tmp;
2855   getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2856                                              NodeEx, BoundEx, *this);
2857   BldrTop.addNodes(Tmp);
2858 }
2859 
2860 std::pair<const ProgramPointTag *, const ProgramPointTag*>
2861 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
2862   static SimpleProgramPointTag
2863          eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
2864                                            "Eagerly Assume True"),
2865          eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
2866                                             "Eagerly Assume False");
2867   return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2868                         &eagerlyAssumeBinOpBifurcationFalse);
2869 }
2870 
2871 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
2872                                                    ExplodedNodeSet &Src,
2873                                                    const Expr *Ex) {
2874   StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2875 
2876   for (const auto Pred : Src) {
2877     // Test if the previous node was as the same expression.  This can happen
2878     // when the expression fails to evaluate to anything meaningful and
2879     // (as an optimization) we don't generate a node.
2880     ProgramPoint P = Pred->getLocation();
2881     if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2882       continue;
2883     }
2884 
2885     ProgramStateRef state = Pred->getState();
2886     SVal V = state->getSVal(Ex, Pred->getLocationContext());
2887     Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
2888     if (SEV && SEV->isExpression()) {
2889       const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2890         geteagerlyAssumeBinOpBifurcationTags();
2891 
2892       ProgramStateRef StateTrue, StateFalse;
2893       std::tie(StateTrue, StateFalse) = state->assume(*SEV);
2894 
2895       // First assume that the condition is true.
2896       if (StateTrue) {
2897         SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2898         StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2899         Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2900       }
2901 
2902       // Next, assume that the condition is false.
2903       if (StateFalse) {
2904         SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2905         StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2906         Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2907       }
2908     }
2909   }
2910 }
2911 
2912 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
2913                                  ExplodedNodeSet &Dst) {
2914   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2915   // We have processed both the inputs and the outputs.  All of the outputs
2916   // should evaluate to Locs.  Nuke all of their values.
2917 
2918   // FIXME: Some day in the future it would be nice to allow a "plug-in"
2919   // which interprets the inline asm and stores proper results in the
2920   // outputs.
2921 
2922   ProgramStateRef state = Pred->getState();
2923 
2924   for (const Expr *O : A->outputs()) {
2925     SVal X = state->getSVal(O, Pred->getLocationContext());
2926     assert(!X.getAs<NonLoc>());  // Should be an Lval, or unknown, undef.
2927 
2928     if (Optional<Loc> LV = X.getAs<Loc>())
2929       state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext());
2930   }
2931 
2932   Bldr.generateNode(A, Pred, state);
2933 }
2934 
2935 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
2936                                 ExplodedNodeSet &Dst) {
2937   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2938   Bldr.generateNode(A, Pred, Pred->getState());
2939 }
2940 
2941 //===----------------------------------------------------------------------===//
2942 // Visualization.
2943 //===----------------------------------------------------------------------===//
2944 
2945 #ifndef NDEBUG
2946 namespace llvm {
2947 
2948 template<>
2949 struct DOTGraphTraits<ExplodedGraph*> : public DefaultDOTGraphTraits {
2950   DOTGraphTraits (bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2951 
2952   static bool nodeHasBugReport(const ExplodedNode *N) {
2953     BugReporter &BR = static_cast<ExprEngine &>(
2954       N->getState()->getStateManager().getOwningEngine()).getBugReporter();
2955 
2956     const auto EQClasses =
2957         llvm::make_range(BR.EQClasses_begin(), BR.EQClasses_end());
2958 
2959     for (const auto &EQ : EQClasses) {
2960       for (const BugReport &Report : EQ) {
2961         if (Report.getErrorNode() == N)
2962           return true;
2963       }
2964     }
2965     return false;
2966   }
2967 
2968   /// \p PreCallback: callback before break.
2969   /// \p PostCallback: callback after break.
2970   /// \p Stop: stop iteration if returns {@code true}
2971   /// \return Whether {@code Stop} ever returned {@code true}.
2972   static bool traverseHiddenNodes(
2973       const ExplodedNode *N,
2974       llvm::function_ref<void(const ExplodedNode *)> PreCallback,
2975       llvm::function_ref<void(const ExplodedNode *)> PostCallback,
2976       llvm::function_ref<bool(const ExplodedNode *)> Stop) {
2977     const ExplodedNode *FirstHiddenNode = N;
2978     while (FirstHiddenNode->pred_size() == 1 &&
2979            isNodeHidden(*FirstHiddenNode->pred_begin())) {
2980       FirstHiddenNode = *FirstHiddenNode->pred_begin();
2981     }
2982     const ExplodedNode *OtherNode = FirstHiddenNode;
2983     while (true) {
2984       PreCallback(OtherNode);
2985       if (Stop(OtherNode))
2986         return true;
2987 
2988       if (OtherNode == N)
2989         break;
2990       PostCallback(OtherNode);
2991 
2992       OtherNode = *OtherNode->succ_begin();
2993     }
2994     return false;
2995   }
2996 
2997   static std::string getNodeAttributes(const ExplodedNode *N,
2998                                        ExplodedGraph *) {
2999     SmallVector<StringRef, 10> Out;
3000     auto Noop = [](const ExplodedNode*){};
3001     if (traverseHiddenNodes(N, Noop, Noop, &nodeHasBugReport)) {
3002       Out.push_back("style=filled");
3003       Out.push_back("fillcolor=red");
3004     }
3005 
3006     if (traverseHiddenNodes(N, Noop, Noop,
3007                             [](const ExplodedNode *C) { return C->isSink(); }))
3008       Out.push_back("color=blue");
3009     return llvm::join(Out, ",");
3010   }
3011 
3012   static bool isNodeHidden(const ExplodedNode *N) {
3013     return N->isTrivial();
3014   }
3015 
3016   static std::string getNodeLabel(const ExplodedNode *N, ExplodedGraph *G){
3017     std::string sbuf;
3018     llvm::raw_string_ostream Out(sbuf);
3019 
3020     ProgramStateRef State = N->getState();
3021 
3022     // Dump program point for all the previously skipped nodes.
3023     traverseHiddenNodes(
3024         N,
3025         [&](const ExplodedNode *OtherNode) {
3026           OtherNode->getLocation().print(/*CR=*/"\\l", Out);
3027           if (const ProgramPointTag *Tag = OtherNode->getLocation().getTag())
3028             Out << "\\lTag:" << Tag->getTagDescription();
3029           if (N->isSink())
3030             Out << "\\lNode is sink\\l";
3031           if (nodeHasBugReport(N))
3032             Out << "\\lBug report attached\\l";
3033         },
3034         [&](const ExplodedNode *) { Out << "\\l--------\\l"; },
3035         [&](const ExplodedNode *) { return false; });
3036 
3037     Out << "\\l\\|";
3038 
3039     Out << "StateID: ST" << State->getID() << ", NodeID: N" << N->getID(G)
3040         << " <" << (const void *)N << ">\\|";
3041 
3042     bool SameAsAllPredecessors =
3043         std::all_of(N->pred_begin(), N->pred_end(), [&](const ExplodedNode *P) {
3044           return P->getState() == State;
3045         });
3046     if (!SameAsAllPredecessors)
3047       State->printDOT(Out, N->getLocationContext());
3048     return Out.str();
3049   }
3050 };
3051 
3052 } // namespace llvm
3053 #endif
3054 
3055 void ExprEngine::ViewGraph(bool trim) {
3056 #ifndef NDEBUG
3057   std::string Filename = DumpGraph(trim);
3058   llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
3059 #endif
3060   llvm::errs() << "Warning: viewing graph requires assertions" << "\n";
3061 }
3062 
3063 
3064 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
3065 #ifndef NDEBUG
3066   std::string Filename = DumpGraph(Nodes);
3067   llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
3068 #endif
3069   llvm::errs() << "Warning: viewing graph requires assertions" << "\n";
3070 }
3071 
3072 std::string ExprEngine::DumpGraph(bool trim, StringRef Filename) {
3073 #ifndef NDEBUG
3074   if (trim) {
3075     std::vector<const ExplodedNode *> Src;
3076 
3077     // Iterate through the reports and get their nodes.
3078     for (BugReporter::EQClasses_iterator
3079            EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
3080       const auto *N = const_cast<ExplodedNode *>(EI->begin()->getErrorNode());
3081       if (N) Src.push_back(N);
3082     }
3083     return DumpGraph(Src, Filename);
3084   } else {
3085     return llvm::WriteGraph(&G, "ExprEngine", /*ShortNames=*/false,
3086                      /*Title=*/"Exploded Graph", /*Filename=*/Filename);
3087   }
3088 #endif
3089   llvm::errs() << "Warning: dumping graph requires assertions" << "\n";
3090   return "";
3091 }
3092 
3093 std::string ExprEngine::DumpGraph(ArrayRef<const ExplodedNode*> Nodes,
3094                                   StringRef Filename) {
3095 #ifndef NDEBUG
3096   std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
3097 
3098   if (!TrimmedG.get()) {
3099     llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
3100   } else {
3101     return llvm::WriteGraph(TrimmedG.get(), "TrimmedExprEngine",
3102                             /*ShortNames=*/false,
3103                             /*Title=*/"Trimmed Exploded Graph",
3104                             /*Filename=*/Filename);
3105   }
3106 #endif
3107   llvm::errs() << "Warning: dumping graph requires assertions" << "\n";
3108   return "";
3109 }
3110 
3111 void *ProgramStateTrait<ReplayWithoutInlining>::GDMIndex() {
3112   static int index = 0;
3113   return &index;
3114 }
3115