1 //===- ExprEngine.cpp - Path-Sensitive Expression-Level Dataflow ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines a meta-engine for path-sensitive dataflow analysis that
11 //  is built on GREngine, but provides the boilerplate to execute transfer
12 //  functions and build the ExplodedGraph at the expression level.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
17 #include "PrettyStackTraceLocationContext.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ParentMap.h"
27 #include "clang/AST/PrettyPrinter.h"
28 #include "clang/AST/Stmt.h"
29 #include "clang/AST/StmtCXX.h"
30 #include "clang/AST/StmtObjC.h"
31 #include "clang/AST/Type.h"
32 #include "clang/Analysis/AnalysisDeclContext.h"
33 #include "clang/Analysis/CFG.h"
34 #include "clang/Analysis/ConstructionContext.h"
35 #include "clang/Analysis/ProgramPoint.h"
36 #include "clang/Basic/IdentifierTable.h"
37 #include "clang/Basic/LLVM.h"
38 #include "clang/Basic/LangOptions.h"
39 #include "clang/Basic/PrettyStackTrace.h"
40 #include "clang/Basic/SourceLocation.h"
41 #include "clang/Basic/SourceManager.h"
42 #include "clang/Basic/Specifiers.h"
43 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
44 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
45 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
46 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
47 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
48 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
49 #include "clang/StaticAnalyzer/Core/PathSensitive/ConstraintManager.h"
50 #include "clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h"
51 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
52 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h"
53 #include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
54 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
55 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
56 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
57 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
58 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
59 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
60 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
61 #include "clang/StaticAnalyzer/Core/PathSensitive/SymExpr.h"
62 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
63 #include "llvm/ADT/APSInt.h"
64 #include "llvm/ADT/DenseMap.h"
65 #include "llvm/ADT/ImmutableMap.h"
66 #include "llvm/ADT/ImmutableSet.h"
67 #include "llvm/ADT/Optional.h"
68 #include "llvm/ADT/SmallVector.h"
69 #include "llvm/ADT/Statistic.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/Compiler.h"
72 #include "llvm/Support/DOTGraphTraits.h"
73 #include "llvm/Support/ErrorHandling.h"
74 #include "llvm/Support/GraphWriter.h"
75 #include "llvm/Support/SaveAndRestore.h"
76 #include "llvm/Support/raw_ostream.h"
77 #include <cassert>
78 #include <cstdint>
79 #include <memory>
80 #include <string>
81 #include <tuple>
82 #include <utility>
83 #include <vector>
84 
85 using namespace clang;
86 using namespace ento;
87 
88 #define DEBUG_TYPE "ExprEngine"
89 
90 STATISTIC(NumRemoveDeadBindings,
91             "The # of times RemoveDeadBindings is called");
92 STATISTIC(NumMaxBlockCountReached,
93             "The # of aborted paths due to reaching the maximum block count in "
94             "a top level function");
95 STATISTIC(NumMaxBlockCountReachedInInlined,
96             "The # of aborted paths due to reaching the maximum block count in "
97             "an inlined function");
98 STATISTIC(NumTimesRetriedWithoutInlining,
99             "The # of times we re-evaluated a call without inlining");
100 
101 //===----------------------------------------------------------------------===//
102 // Internal program state traits.
103 //===----------------------------------------------------------------------===//
104 
105 namespace {
106 
107 // When modeling a C++ constructor, for a variety of reasons we need to track
108 // the location of the object for the duration of its ConstructionContext.
109 // ObjectsUnderConstruction maps statements within the construction context
110 // to the object's location, so that on every such statement the location
111 // could have been retrieved.
112 
113 /// ConstructedObjectKey is used for being able to find the path-sensitive
114 /// memory region of a freshly constructed object while modeling the AST node
115 /// that syntactically represents the object that is being constructed.
116 /// Semantics of such nodes may sometimes require access to the region that's
117 /// not otherwise present in the program state, or to the very fact that
118 /// the construction context was present and contained references to these
119 /// AST nodes.
120 class ConstructedObjectKey {
121   typedef std::pair<ConstructionContextItem, const LocationContext *>
122       ConstructedObjectKeyImpl;
123 
124   const ConstructedObjectKeyImpl Impl;
125 
126   const void *getAnyASTNodePtr() const {
127     if (const Stmt *S = getItem().getStmtOrNull())
128       return S;
129     else
130       return getItem().getCXXCtorInitializer();
131   }
132 
133 public:
134   explicit ConstructedObjectKey(const ConstructionContextItem &Item,
135                        const LocationContext *LC)
136       : Impl(Item, LC) {}
137 
138   const ConstructionContextItem &getItem() const { return Impl.first; }
139   const LocationContext *getLocationContext() const { return Impl.second; }
140 
141   void print(llvm::raw_ostream &OS, PrinterHelper *Helper, PrintingPolicy &PP) {
142     OS << '(' << getLocationContext() << ',' << getAnyASTNodePtr() << ','
143        << getItem().getKindAsString();
144     if (getItem().getKind() == ConstructionContextItem::ArgumentKind)
145       OS << " #" << getItem().getIndex();
146     OS << ") ";
147     if (const Stmt *S = getItem().getStmtOrNull()) {
148       S->printPretty(OS, Helper, PP);
149     } else {
150       const CXXCtorInitializer *I = getItem().getCXXCtorInitializer();
151       OS << I->getAnyMember()->getNameAsString();
152     }
153   }
154 
155   void Profile(llvm::FoldingSetNodeID &ID) const {
156     ID.Add(Impl.first);
157     ID.AddPointer(Impl.second);
158   }
159 
160   bool operator==(const ConstructedObjectKey &RHS) const {
161     return Impl == RHS.Impl;
162   }
163 
164   bool operator<(const ConstructedObjectKey &RHS) const {
165     return Impl < RHS.Impl;
166   }
167 };
168 } // namespace
169 
170 typedef llvm::ImmutableMap<ConstructedObjectKey, SVal>
171     ObjectsUnderConstructionMap;
172 REGISTER_TRAIT_WITH_PROGRAMSTATE(ObjectsUnderConstruction,
173                                  ObjectsUnderConstructionMap)
174 
175 //===----------------------------------------------------------------------===//
176 // Engine construction and deletion.
177 //===----------------------------------------------------------------------===//
178 
179 static const char* TagProviderName = "ExprEngine";
180 
181 ExprEngine::ExprEngine(cross_tu::CrossTranslationUnitContext &CTU,
182                        AnalysisManager &mgr,
183                        SetOfConstDecls *VisitedCalleesIn,
184                        FunctionSummariesTy *FS,
185                        InliningModes HowToInlineIn)
186     : CTU(CTU), AMgr(mgr),
187       AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
188       Engine(*this, FS, mgr.getAnalyzerOptions()), G(Engine.getGraph()),
189       StateMgr(getContext(), mgr.getStoreManagerCreator(),
190                mgr.getConstraintManagerCreator(), G.getAllocator(),
191                this),
192       SymMgr(StateMgr.getSymbolManager()),
193       svalBuilder(StateMgr.getSValBuilder()), ObjCNoRet(mgr.getASTContext()),
194       BR(mgr, *this),
195       VisitedCallees(VisitedCalleesIn), HowToInline(HowToInlineIn) {
196   unsigned TrimInterval = mgr.options.getGraphTrimInterval();
197   if (TrimInterval != 0) {
198     // Enable eager node reclaimation when constructing the ExplodedGraph.
199     G.enableNodeReclamation(TrimInterval);
200   }
201 }
202 
203 ExprEngine::~ExprEngine() {
204   BR.FlushReports();
205 }
206 
207 //===----------------------------------------------------------------------===//
208 // Utility methods.
209 //===----------------------------------------------------------------------===//
210 
211 ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
212   ProgramStateRef state = StateMgr.getInitialState(InitLoc);
213   const Decl *D = InitLoc->getDecl();
214 
215   // Preconditions.
216   // FIXME: It would be nice if we had a more general mechanism to add
217   // such preconditions.  Some day.
218   do {
219     if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
220       // Precondition: the first argument of 'main' is an integer guaranteed
221       //  to be > 0.
222       const IdentifierInfo *II = FD->getIdentifier();
223       if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
224         break;
225 
226       const ParmVarDecl *PD = FD->getParamDecl(0);
227       QualType T = PD->getType();
228       const auto *BT = dyn_cast<BuiltinType>(T);
229       if (!BT || !BT->isInteger())
230         break;
231 
232       const MemRegion *R = state->getRegion(PD, InitLoc);
233       if (!R)
234         break;
235 
236       SVal V = state->getSVal(loc::MemRegionVal(R));
237       SVal Constraint_untested = evalBinOp(state, BO_GT, V,
238                                            svalBuilder.makeZeroVal(T),
239                                            svalBuilder.getConditionType());
240 
241       Optional<DefinedOrUnknownSVal> Constraint =
242           Constraint_untested.getAs<DefinedOrUnknownSVal>();
243 
244       if (!Constraint)
245         break;
246 
247       if (ProgramStateRef newState = state->assume(*Constraint, true))
248         state = newState;
249     }
250     break;
251   }
252   while (false);
253 
254   if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
255     // Precondition: 'self' is always non-null upon entry to an Objective-C
256     // method.
257     const ImplicitParamDecl *SelfD = MD->getSelfDecl();
258     const MemRegion *R = state->getRegion(SelfD, InitLoc);
259     SVal V = state->getSVal(loc::MemRegionVal(R));
260 
261     if (Optional<Loc> LV = V.getAs<Loc>()) {
262       // Assume that the pointer value in 'self' is non-null.
263       state = state->assume(*LV, true);
264       assert(state && "'self' cannot be null");
265     }
266   }
267 
268   if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
269     if (!MD->isStatic()) {
270       // Precondition: 'this' is always non-null upon entry to the
271       // top-level function.  This is our starting assumption for
272       // analyzing an "open" program.
273       const StackFrameContext *SFC = InitLoc->getStackFrame();
274       if (SFC->getParent() == nullptr) {
275         loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
276         SVal V = state->getSVal(L);
277         if (Optional<Loc> LV = V.getAs<Loc>()) {
278           state = state->assume(*LV, true);
279           assert(state && "'this' cannot be null");
280         }
281       }
282     }
283   }
284 
285   return state;
286 }
287 
288 ProgramStateRef ExprEngine::createTemporaryRegionIfNeeded(
289     ProgramStateRef State, const LocationContext *LC,
290     const Expr *InitWithAdjustments, const Expr *Result,
291     const SubRegion **OutRegionWithAdjustments) {
292   // FIXME: This function is a hack that works around the quirky AST
293   // we're often having with respect to C++ temporaries. If only we modelled
294   // the actual execution order of statements properly in the CFG,
295   // all the hassle with adjustments would not be necessary,
296   // and perhaps the whole function would be removed.
297   SVal InitValWithAdjustments = State->getSVal(InitWithAdjustments, LC);
298   if (!Result) {
299     // If we don't have an explicit result expression, we're in "if needed"
300     // mode. Only create a region if the current value is a NonLoc.
301     if (!InitValWithAdjustments.getAs<NonLoc>()) {
302       if (OutRegionWithAdjustments)
303         *OutRegionWithAdjustments = nullptr;
304       return State;
305     }
306     Result = InitWithAdjustments;
307   } else {
308     // We need to create a region no matter what. For sanity, make sure we don't
309     // try to stuff a Loc into a non-pointer temporary region.
310     assert(!InitValWithAdjustments.getAs<Loc>() ||
311            Loc::isLocType(Result->getType()) ||
312            Result->getType()->isMemberPointerType());
313   }
314 
315   ProgramStateManager &StateMgr = State->getStateManager();
316   MemRegionManager &MRMgr = StateMgr.getRegionManager();
317   StoreManager &StoreMgr = StateMgr.getStoreManager();
318 
319   // MaterializeTemporaryExpr may appear out of place, after a few field and
320   // base-class accesses have been made to the object, even though semantically
321   // it is the whole object that gets materialized and lifetime-extended.
322   //
323   // For example:
324   //
325   //   `-MaterializeTemporaryExpr
326   //     `-MemberExpr
327   //       `-CXXTemporaryObjectExpr
328   //
329   // instead of the more natural
330   //
331   //   `-MemberExpr
332   //     `-MaterializeTemporaryExpr
333   //       `-CXXTemporaryObjectExpr
334   //
335   // Use the usual methods for obtaining the expression of the base object,
336   // and record the adjustments that we need to make to obtain the sub-object
337   // that the whole expression 'Ex' refers to. This trick is usual,
338   // in the sense that CodeGen takes a similar route.
339 
340   SmallVector<const Expr *, 2> CommaLHSs;
341   SmallVector<SubobjectAdjustment, 2> Adjustments;
342 
343   const Expr *Init = InitWithAdjustments->skipRValueSubobjectAdjustments(
344       CommaLHSs, Adjustments);
345 
346   // Take the region for Init, i.e. for the whole object. If we do not remember
347   // the region in which the object originally was constructed, come up with
348   // a new temporary region out of thin air and copy the contents of the object
349   // (which are currently present in the Environment, because Init is an rvalue)
350   // into that region. This is not correct, but it is better than nothing.
351   const TypedValueRegion *TR = nullptr;
352   if (const auto *MT = dyn_cast<MaterializeTemporaryExpr>(Result)) {
353     if (Optional<SVal> V = getObjectUnderConstruction(State, MT, LC)) {
354       State = finishObjectConstruction(State, MT, LC);
355       State = State->BindExpr(Result, LC, *V);
356       return State;
357     } else {
358       StorageDuration SD = MT->getStorageDuration();
359       // If this object is bound to a reference with static storage duration, we
360       // put it in a different region to prevent "address leakage" warnings.
361       if (SD == SD_Static || SD == SD_Thread) {
362         TR = MRMgr.getCXXStaticTempObjectRegion(Init);
363       } else {
364         TR = MRMgr.getCXXTempObjectRegion(Init, LC);
365       }
366     }
367   } else {
368     TR = MRMgr.getCXXTempObjectRegion(Init, LC);
369   }
370 
371   SVal Reg = loc::MemRegionVal(TR);
372   SVal BaseReg = Reg;
373 
374   // Make the necessary adjustments to obtain the sub-object.
375   for (auto I = Adjustments.rbegin(), E = Adjustments.rend(); I != E; ++I) {
376     const SubobjectAdjustment &Adj = *I;
377     switch (Adj.Kind) {
378     case SubobjectAdjustment::DerivedToBaseAdjustment:
379       Reg = StoreMgr.evalDerivedToBase(Reg, Adj.DerivedToBase.BasePath);
380       break;
381     case SubobjectAdjustment::FieldAdjustment:
382       Reg = StoreMgr.getLValueField(Adj.Field, Reg);
383       break;
384     case SubobjectAdjustment::MemberPointerAdjustment:
385       // FIXME: Unimplemented.
386       State = State->invalidateRegions(Reg, InitWithAdjustments,
387                                        currBldrCtx->blockCount(), LC, true,
388                                        nullptr, nullptr, nullptr);
389       return State;
390     }
391   }
392 
393   // What remains is to copy the value of the object to the new region.
394   // FIXME: In other words, what we should always do is copy value of the
395   // Init expression (which corresponds to the bigger object) to the whole
396   // temporary region TR. However, this value is often no longer present
397   // in the Environment. If it has disappeared, we instead invalidate TR.
398   // Still, what we can do is assign the value of expression Ex (which
399   // corresponds to the sub-object) to the TR's sub-region Reg. At least,
400   // values inside Reg would be correct.
401   SVal InitVal = State->getSVal(Init, LC);
402   if (InitVal.isUnknown()) {
403     InitVal = getSValBuilder().conjureSymbolVal(Result, LC, Init->getType(),
404                                                 currBldrCtx->blockCount());
405     State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
406 
407     // Then we'd need to take the value that certainly exists and bind it
408     // over.
409     if (InitValWithAdjustments.isUnknown()) {
410       // Try to recover some path sensitivity in case we couldn't
411       // compute the value.
412       InitValWithAdjustments = getSValBuilder().conjureSymbolVal(
413           Result, LC, InitWithAdjustments->getType(),
414           currBldrCtx->blockCount());
415     }
416     State =
417         State->bindLoc(Reg.castAs<Loc>(), InitValWithAdjustments, LC, false);
418   } else {
419     State = State->bindLoc(BaseReg.castAs<Loc>(), InitVal, LC, false);
420   }
421 
422   // The result expression would now point to the correct sub-region of the
423   // newly created temporary region. Do this last in order to getSVal of Init
424   // correctly in case (Result == Init).
425   if (Result->isGLValue()) {
426     State = State->BindExpr(Result, LC, Reg);
427   } else {
428     State = State->BindExpr(Result, LC, InitValWithAdjustments);
429   }
430 
431   // Notify checkers once for two bindLoc()s.
432   State = processRegionChange(State, TR, LC);
433 
434   if (OutRegionWithAdjustments)
435     *OutRegionWithAdjustments = cast<SubRegion>(Reg.getAsRegion());
436   return State;
437 }
438 
439 ProgramStateRef
440 ExprEngine::addObjectUnderConstruction(ProgramStateRef State,
441                                        const ConstructionContextItem &Item,
442                                        const LocationContext *LC, SVal V) {
443   ConstructedObjectKey Key(Item, LC->getStackFrame());
444   // FIXME: Currently the state might already contain the marker due to
445   // incorrect handling of temporaries bound to default parameters.
446   assert(!State->get<ObjectsUnderConstruction>(Key) ||
447          Key.getItem().getKind() ==
448              ConstructionContextItem::TemporaryDestructorKind);
449   return State->set<ObjectsUnderConstruction>(Key, V);
450 }
451 
452 Optional<SVal>
453 ExprEngine::getObjectUnderConstruction(ProgramStateRef State,
454                                        const ConstructionContextItem &Item,
455                                        const LocationContext *LC) {
456   ConstructedObjectKey Key(Item, LC->getStackFrame());
457   return Optional<SVal>::create(State->get<ObjectsUnderConstruction>(Key));
458 }
459 
460 ProgramStateRef
461 ExprEngine::finishObjectConstruction(ProgramStateRef State,
462                                      const ConstructionContextItem &Item,
463                                      const LocationContext *LC) {
464   ConstructedObjectKey Key(Item, LC->getStackFrame());
465   assert(State->contains<ObjectsUnderConstruction>(Key));
466   return State->remove<ObjectsUnderConstruction>(Key);
467 }
468 
469 ProgramStateRef ExprEngine::elideDestructor(ProgramStateRef State,
470                                             const CXXBindTemporaryExpr *BTE,
471                                             const LocationContext *LC) {
472   ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
473   // FIXME: Currently the state might already contain the marker due to
474   // incorrect handling of temporaries bound to default parameters.
475   return State->set<ObjectsUnderConstruction>(Key, UnknownVal());
476 }
477 
478 ProgramStateRef
479 ExprEngine::cleanupElidedDestructor(ProgramStateRef State,
480                                     const CXXBindTemporaryExpr *BTE,
481                                     const LocationContext *LC) {
482   ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
483   assert(State->contains<ObjectsUnderConstruction>(Key));
484   return State->remove<ObjectsUnderConstruction>(Key);
485 }
486 
487 bool ExprEngine::isDestructorElided(ProgramStateRef State,
488                                     const CXXBindTemporaryExpr *BTE,
489                                     const LocationContext *LC) {
490   ConstructedObjectKey Key({BTE, /*IsElided=*/true}, LC);
491   return State->contains<ObjectsUnderConstruction>(Key);
492 }
493 
494 bool ExprEngine::areAllObjectsFullyConstructed(ProgramStateRef State,
495                                                const LocationContext *FromLC,
496                                                const LocationContext *ToLC) {
497   const LocationContext *LC = FromLC;
498   while (LC != ToLC) {
499     assert(LC && "ToLC must be a parent of FromLC!");
500     for (auto I : State->get<ObjectsUnderConstruction>())
501       if (I.first.getLocationContext() == LC)
502         return false;
503 
504     LC = LC->getParent();
505   }
506   return true;
507 }
508 
509 
510 //===----------------------------------------------------------------------===//
511 // Top-level transfer function logic (Dispatcher).
512 //===----------------------------------------------------------------------===//
513 
514 /// evalAssume - Called by ConstraintManager. Used to call checker-specific
515 ///  logic for handling assumptions on symbolic values.
516 ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
517                                               SVal cond, bool assumption) {
518   return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
519 }
520 
521 ProgramStateRef
522 ExprEngine::processRegionChanges(ProgramStateRef state,
523                                  const InvalidatedSymbols *invalidated,
524                                  ArrayRef<const MemRegion *> Explicits,
525                                  ArrayRef<const MemRegion *> Regions,
526                                  const LocationContext *LCtx,
527                                  const CallEvent *Call) {
528   return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
529                                                          Explicits, Regions,
530                                                          LCtx, Call);
531 }
532 
533 static void printObjectsUnderConstructionForContext(raw_ostream &Out,
534                                                     ProgramStateRef State,
535                                                     const char *NL,
536                                                     const LocationContext *LC) {
537   PrintingPolicy PP =
538       LC->getAnalysisDeclContext()->getASTContext().getPrintingPolicy();
539   for (auto I : State->get<ObjectsUnderConstruction>()) {
540     ConstructedObjectKey Key = I.first;
541     SVal Value = I.second;
542     if (Key.getLocationContext() != LC)
543       continue;
544     Key.print(Out, nullptr, PP);
545     Out << " : " << Value << NL;
546   }
547 }
548 
549 void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
550                             const char *NL, const char *Sep,
551                             const LocationContext *LCtx) {
552   if (LCtx) {
553     if (!State->get<ObjectsUnderConstruction>().isEmpty()) {
554       Out << Sep << "Objects under construction:" << NL;
555 
556       LCtx->dumpStack(Out, "", NL, Sep, [&](const LocationContext *LC) {
557         printObjectsUnderConstructionForContext(Out, State, NL, LC);
558       });
559     }
560   }
561 
562   getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
563 }
564 
565 void ExprEngine::processEndWorklist() {
566   getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
567 }
568 
569 void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
570                                    unsigned StmtIdx, NodeBuilderContext *Ctx) {
571   PrettyStackTraceLocationContext CrashInfo(Pred->getLocationContext());
572   currStmtIdx = StmtIdx;
573   currBldrCtx = Ctx;
574 
575   switch (E.getKind()) {
576     case CFGElement::Statement:
577     case CFGElement::Constructor:
578     case CFGElement::CXXRecordTypedCall:
579       ProcessStmt(E.castAs<CFGStmt>().getStmt(), Pred);
580       return;
581     case CFGElement::Initializer:
582       ProcessInitializer(E.castAs<CFGInitializer>(), Pred);
583       return;
584     case CFGElement::NewAllocator:
585       ProcessNewAllocator(E.castAs<CFGNewAllocator>().getAllocatorExpr(),
586                           Pred);
587       return;
588     case CFGElement::AutomaticObjectDtor:
589     case CFGElement::DeleteDtor:
590     case CFGElement::BaseDtor:
591     case CFGElement::MemberDtor:
592     case CFGElement::TemporaryDtor:
593       ProcessImplicitDtor(E.castAs<CFGImplicitDtor>(), Pred);
594       return;
595     case CFGElement::LoopExit:
596       ProcessLoopExit(E.castAs<CFGLoopExit>().getLoopStmt(), Pred);
597       return;
598     case CFGElement::LifetimeEnds:
599     case CFGElement::ScopeBegin:
600     case CFGElement::ScopeEnd:
601       return;
602   }
603 }
604 
605 static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
606                                      const Stmt *S,
607                                      const ExplodedNode *Pred,
608                                      const LocationContext *LC) {
609   // Are we never purging state values?
610   if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
611     return false;
612 
613   // Is this the beginning of a basic block?
614   if (Pred->getLocation().getAs<BlockEntrance>())
615     return true;
616 
617   // Is this on a non-expression?
618   if (!isa<Expr>(S))
619     return true;
620 
621   // Run before processing a call.
622   if (CallEvent::isCallStmt(S))
623     return true;
624 
625   // Is this an expression that is consumed by another expression?  If so,
626   // postpone cleaning out the state.
627   ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
628   return !PM.isConsumedExpr(cast<Expr>(S));
629 }
630 
631 void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
632                             const Stmt *ReferenceStmt,
633                             const LocationContext *LC,
634                             const Stmt *DiagnosticStmt,
635                             ProgramPoint::Kind K) {
636   assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
637           ReferenceStmt == nullptr || isa<ReturnStmt>(ReferenceStmt))
638           && "PostStmt is not generally supported by the SymbolReaper yet");
639   assert(LC && "Must pass the current (or expiring) LocationContext");
640 
641   if (!DiagnosticStmt) {
642     DiagnosticStmt = ReferenceStmt;
643     assert(DiagnosticStmt && "Required for clearing a LocationContext");
644   }
645 
646   NumRemoveDeadBindings++;
647   ProgramStateRef CleanedState = Pred->getState();
648 
649   // LC is the location context being destroyed, but SymbolReaper wants a
650   // location context that is still live. (If this is the top-level stack
651   // frame, this will be null.)
652   if (!ReferenceStmt) {
653     assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
654            "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
655     LC = LC->getParent();
656   }
657 
658   const StackFrameContext *SFC = LC ? LC->getStackFrame() : nullptr;
659   SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
660 
661   for (auto I : CleanedState->get<ObjectsUnderConstruction>()) {
662     if (SymbolRef Sym = I.second.getAsSymbol())
663       SymReaper.markLive(Sym);
664     if (const MemRegion *MR = I.second.getAsRegion())
665       SymReaper.markLive(MR);
666   }
667 
668   getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
669 
670   // Create a state in which dead bindings are removed from the environment
671   // and the store. TODO: The function should just return new env and store,
672   // not a new state.
673   CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
674 
675   // Process any special transfer function for dead symbols.
676   // A tag to track convenience transitions, which can be removed at cleanup.
677   static SimpleProgramPointTag cleanupTag(TagProviderName, "Clean Node");
678   if (!SymReaper.hasDeadSymbols()) {
679     // Generate a CleanedNode that has the environment and store cleaned
680     // up. Since no symbols are dead, we can optimize and not clean out
681     // the constraint manager.
682     StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx);
683     Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K);
684 
685   } else {
686     // Call checkers with the non-cleaned state so that they could query the
687     // values of the soon to be dead symbols.
688     ExplodedNodeSet CheckedSet;
689     getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
690                                                   DiagnosticStmt, *this, K);
691 
692     // For each node in CheckedSet, generate CleanedNodes that have the
693     // environment, the store, and the constraints cleaned up but have the
694     // user-supplied states as the predecessors.
695     StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
696     for (const auto I : CheckedSet) {
697       ProgramStateRef CheckerState = I->getState();
698 
699       // The constraint manager has not been cleaned up yet, so clean up now.
700       CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
701                                                                SymReaper);
702 
703       assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
704         "Checkers are not allowed to modify the Environment as a part of "
705         "checkDeadSymbols processing.");
706       assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
707         "Checkers are not allowed to modify the Store as a part of "
708         "checkDeadSymbols processing.");
709 
710       // Create a state based on CleanedState with CheckerState GDM and
711       // generate a transition to that state.
712       ProgramStateRef CleanedCheckerSt =
713         StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
714       Bldr.generateNode(DiagnosticStmt, I, CleanedCheckerSt, &cleanupTag, K);
715     }
716   }
717 }
718 
719 void ExprEngine::ProcessStmt(const Stmt *currStmt, ExplodedNode *Pred) {
720   // Reclaim any unnecessary nodes in the ExplodedGraph.
721   G.reclaimRecentlyAllocatedNodes();
722 
723   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
724                                 currStmt->getBeginLoc(),
725                                 "Error evaluating statement");
726 
727   // Remove dead bindings and symbols.
728   ExplodedNodeSet CleanedStates;
729   if (shouldRemoveDeadBindings(AMgr, currStmt, Pred,
730                                Pred->getLocationContext())) {
731     removeDead(Pred, CleanedStates, currStmt,
732                                     Pred->getLocationContext());
733   } else
734     CleanedStates.Add(Pred);
735 
736   // Visit the statement.
737   ExplodedNodeSet Dst;
738   for (const auto I : CleanedStates) {
739     ExplodedNodeSet DstI;
740     // Visit the statement.
741     Visit(currStmt, I, DstI);
742     Dst.insert(DstI);
743   }
744 
745   // Enqueue the new nodes onto the work list.
746   Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
747 }
748 
749 void ExprEngine::ProcessLoopExit(const Stmt* S, ExplodedNode *Pred) {
750   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
751                                 S->getBeginLoc(),
752                                 "Error evaluating end of the loop");
753   ExplodedNodeSet Dst;
754   Dst.Add(Pred);
755   NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
756   ProgramStateRef NewState = Pred->getState();
757 
758   if(AMgr.options.shouldUnrollLoops())
759     NewState = processLoopEnd(S, NewState);
760 
761   LoopExit PP(S, Pred->getLocationContext());
762   Bldr.generateNode(PP, NewState, Pred);
763   // Enqueue the new nodes onto the work list.
764   Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
765 }
766 
767 void ExprEngine::ProcessInitializer(const CFGInitializer CFGInit,
768                                     ExplodedNode *Pred) {
769   const CXXCtorInitializer *BMI = CFGInit.getInitializer();
770   const Expr *Init = BMI->getInit()->IgnoreImplicit();
771   const LocationContext *LC = Pred->getLocationContext();
772 
773   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
774                                 BMI->getSourceLocation(),
775                                 "Error evaluating initializer");
776 
777   // We don't clean up dead bindings here.
778   const auto *stackFrame = cast<StackFrameContext>(Pred->getLocationContext());
779   const auto *decl = cast<CXXConstructorDecl>(stackFrame->getDecl());
780 
781   ProgramStateRef State = Pred->getState();
782   SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
783 
784   ExplodedNodeSet Tmp;
785   SVal FieldLoc;
786 
787   // Evaluate the initializer, if necessary
788   if (BMI->isAnyMemberInitializer()) {
789     // Constructors build the object directly in the field,
790     // but non-objects must be copied in from the initializer.
791     if (getObjectUnderConstruction(State, BMI, LC)) {
792       // The field was directly constructed, so there is no need to bind.
793       // But we still need to stop tracking the object under construction.
794       State = finishObjectConstruction(State, BMI, LC);
795       NodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
796       PostStore PS(Init, LC, /*Loc*/ nullptr, /*tag*/ nullptr);
797       Bldr.generateNode(PS, State, Pred);
798     } else {
799       const ValueDecl *Field;
800       if (BMI->isIndirectMemberInitializer()) {
801         Field = BMI->getIndirectMember();
802         FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
803       } else {
804         Field = BMI->getMember();
805         FieldLoc = State->getLValue(BMI->getMember(), thisVal);
806       }
807 
808       SVal InitVal;
809       if (Init->getType()->isArrayType()) {
810         // Handle arrays of trivial type. We can represent this with a
811         // primitive load/copy from the base array region.
812         const ArraySubscriptExpr *ASE;
813         while ((ASE = dyn_cast<ArraySubscriptExpr>(Init)))
814           Init = ASE->getBase()->IgnoreImplicit();
815 
816         SVal LValue = State->getSVal(Init, stackFrame);
817         if (!Field->getType()->isReferenceType())
818           if (Optional<Loc> LValueLoc = LValue.getAs<Loc>())
819             InitVal = State->getSVal(*LValueLoc);
820 
821         // If we fail to get the value for some reason, use a symbolic value.
822         if (InitVal.isUnknownOrUndef()) {
823           SValBuilder &SVB = getSValBuilder();
824           InitVal = SVB.conjureSymbolVal(BMI->getInit(), stackFrame,
825                                          Field->getType(),
826                                          currBldrCtx->blockCount());
827         }
828       } else {
829         InitVal = State->getSVal(BMI->getInit(), stackFrame);
830       }
831 
832       PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
833       evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
834     }
835   } else {
836     assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
837     Tmp.insert(Pred);
838     // We already did all the work when visiting the CXXConstructExpr.
839   }
840 
841   // Construct PostInitializer nodes whether the state changed or not,
842   // so that the diagnostics don't get confused.
843   PostInitializer PP(BMI, FieldLoc.getAsRegion(), stackFrame);
844   ExplodedNodeSet Dst;
845   NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
846   for (const auto I : Tmp) {
847     ProgramStateRef State = I->getState();
848     Bldr.generateNode(PP, State, I);
849   }
850 
851   // Enqueue the new nodes onto the work list.
852   Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
853 }
854 
855 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
856                                      ExplodedNode *Pred) {
857   ExplodedNodeSet Dst;
858   switch (D.getKind()) {
859   case CFGElement::AutomaticObjectDtor:
860     ProcessAutomaticObjDtor(D.castAs<CFGAutomaticObjDtor>(), Pred, Dst);
861     break;
862   case CFGElement::BaseDtor:
863     ProcessBaseDtor(D.castAs<CFGBaseDtor>(), Pred, Dst);
864     break;
865   case CFGElement::MemberDtor:
866     ProcessMemberDtor(D.castAs<CFGMemberDtor>(), Pred, Dst);
867     break;
868   case CFGElement::TemporaryDtor:
869     ProcessTemporaryDtor(D.castAs<CFGTemporaryDtor>(), Pred, Dst);
870     break;
871   case CFGElement::DeleteDtor:
872     ProcessDeleteDtor(D.castAs<CFGDeleteDtor>(), Pred, Dst);
873     break;
874   default:
875     llvm_unreachable("Unexpected dtor kind.");
876   }
877 
878   // Enqueue the new nodes onto the work list.
879   Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
880 }
881 
882 void ExprEngine::ProcessNewAllocator(const CXXNewExpr *NE,
883                                      ExplodedNode *Pred) {
884   ExplodedNodeSet Dst;
885   AnalysisManager &AMgr = getAnalysisManager();
886   AnalyzerOptions &Opts = AMgr.options;
887   // TODO: We're not evaluating allocators for all cases just yet as
888   // we're not handling the return value correctly, which causes false
889   // positives when the alpha.cplusplus.NewDeleteLeaks check is on.
890   if (Opts.mayInlineCXXAllocator())
891     VisitCXXNewAllocatorCall(NE, Pred, Dst);
892   else {
893     NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
894     const LocationContext *LCtx = Pred->getLocationContext();
895     PostImplicitCall PP(NE->getOperatorNew(), NE->getBeginLoc(), LCtx);
896     Bldr.generateNode(PP, Pred->getState(), Pred);
897   }
898   Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
899 }
900 
901 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
902                                          ExplodedNode *Pred,
903                                          ExplodedNodeSet &Dst) {
904   const VarDecl *varDecl = Dtor.getVarDecl();
905   QualType varType = varDecl->getType();
906 
907   ProgramStateRef state = Pred->getState();
908   SVal dest = state->getLValue(varDecl, Pred->getLocationContext());
909   const MemRegion *Region = dest.castAs<loc::MemRegionVal>().getRegion();
910 
911   if (varType->isReferenceType()) {
912     const MemRegion *ValueRegion = state->getSVal(Region).getAsRegion();
913     if (!ValueRegion) {
914       // FIXME: This should not happen. The language guarantees a presence
915       // of a valid initializer here, so the reference shall not be undefined.
916       // It seems that we're calling destructors over variables that
917       // were not initialized yet.
918       return;
919     }
920     Region = ValueRegion->getBaseRegion();
921     varType = cast<TypedValueRegion>(Region)->getValueType();
922   }
923 
924   // FIXME: We need to run the same destructor on every element of the array.
925   // This workaround will just run the first destructor (which will still
926   // invalidate the entire array).
927   EvalCallOptions CallOpts;
928   Region = makeZeroElementRegion(state, loc::MemRegionVal(Region), varType,
929                                  CallOpts.IsArrayCtorOrDtor).getAsRegion();
930 
931   VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(), /*IsBase=*/ false,
932                      Pred, Dst, CallOpts);
933 }
934 
935 void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor Dtor,
936                                    ExplodedNode *Pred,
937                                    ExplodedNodeSet &Dst) {
938   ProgramStateRef State = Pred->getState();
939   const LocationContext *LCtx = Pred->getLocationContext();
940   const CXXDeleteExpr *DE = Dtor.getDeleteExpr();
941   const Stmt *Arg = DE->getArgument();
942   QualType DTy = DE->getDestroyedType();
943   SVal ArgVal = State->getSVal(Arg, LCtx);
944 
945   // If the argument to delete is known to be a null value,
946   // don't run destructor.
947   if (State->isNull(ArgVal).isConstrainedTrue()) {
948     QualType BTy = getContext().getBaseElementType(DTy);
949     const CXXRecordDecl *RD = BTy->getAsCXXRecordDecl();
950     const CXXDestructorDecl *Dtor = RD->getDestructor();
951 
952     PostImplicitCall PP(Dtor, DE->getBeginLoc(), LCtx);
953     NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
954     Bldr.generateNode(PP, Pred->getState(), Pred);
955     return;
956   }
957 
958   EvalCallOptions CallOpts;
959   const MemRegion *ArgR = ArgVal.getAsRegion();
960   if (DE->isArrayForm()) {
961     // FIXME: We need to run the same destructor on every element of the array.
962     // This workaround will just run the first destructor (which will still
963     // invalidate the entire array).
964     CallOpts.IsArrayCtorOrDtor = true;
965     // Yes, it may even be a multi-dimensional array.
966     while (const auto *AT = getContext().getAsArrayType(DTy))
967       DTy = AT->getElementType();
968     if (ArgR)
969       ArgR = getStoreManager().GetElementZeroRegion(cast<SubRegion>(ArgR), DTy);
970   }
971 
972   VisitCXXDestructor(DTy, ArgR, DE, /*IsBase=*/false, Pred, Dst, CallOpts);
973 }
974 
975 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
976                                  ExplodedNode *Pred, ExplodedNodeSet &Dst) {
977   const LocationContext *LCtx = Pred->getLocationContext();
978 
979   const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
980   Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
981                                             LCtx->getStackFrame());
982   SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
983 
984   // Create the base object region.
985   const CXXBaseSpecifier *Base = D.getBaseSpecifier();
986   QualType BaseTy = Base->getType();
987   SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy,
988                                                      Base->isVirtual());
989 
990   VisitCXXDestructor(BaseTy, BaseVal.castAs<loc::MemRegionVal>().getRegion(),
991                      CurDtor->getBody(), /*IsBase=*/ true, Pred, Dst, {});
992 }
993 
994 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
995                                    ExplodedNode *Pred, ExplodedNodeSet &Dst) {
996   const FieldDecl *Member = D.getFieldDecl();
997   QualType T = Member->getType();
998   ProgramStateRef State = Pred->getState();
999   const LocationContext *LCtx = Pred->getLocationContext();
1000 
1001   const auto *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
1002   Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
1003                                             LCtx->getStackFrame());
1004   SVal FieldVal =
1005       State->getLValue(Member, State->getSVal(ThisVal).castAs<Loc>());
1006 
1007   // FIXME: We need to run the same destructor on every element of the array.
1008   // This workaround will just run the first destructor (which will still
1009   // invalidate the entire array).
1010   EvalCallOptions CallOpts;
1011   FieldVal = makeZeroElementRegion(State, FieldVal, T,
1012                                    CallOpts.IsArrayCtorOrDtor);
1013 
1014   VisitCXXDestructor(T, FieldVal.castAs<loc::MemRegionVal>().getRegion(),
1015                      CurDtor->getBody(), /*IsBase=*/false, Pred, Dst, CallOpts);
1016 }
1017 
1018 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
1019                                       ExplodedNode *Pred,
1020                                       ExplodedNodeSet &Dst) {
1021   const CXXBindTemporaryExpr *BTE = D.getBindTemporaryExpr();
1022   ProgramStateRef State = Pred->getState();
1023   const LocationContext *LC = Pred->getLocationContext();
1024   const MemRegion *MR = nullptr;
1025 
1026   if (Optional<SVal> V =
1027           getObjectUnderConstruction(State, D.getBindTemporaryExpr(),
1028                                      Pred->getLocationContext())) {
1029     // FIXME: Currently we insert temporary destructors for default parameters,
1030     // but we don't insert the constructors, so the entry in
1031     // ObjectsUnderConstruction may be missing.
1032     State = finishObjectConstruction(State, D.getBindTemporaryExpr(),
1033                                      Pred->getLocationContext());
1034     MR = V->getAsRegion();
1035   }
1036 
1037   // If copy elision has occured, and the constructor corresponding to the
1038   // destructor was elided, we need to skip the destructor as well.
1039   if (isDestructorElided(State, BTE, LC)) {
1040     State = cleanupElidedDestructor(State, BTE, LC);
1041     NodeBuilder Bldr(Pred, Dst, *currBldrCtx);
1042     PostImplicitCall PP(D.getDestructorDecl(getContext()),
1043                         D.getBindTemporaryExpr()->getBeginLoc(),
1044                         Pred->getLocationContext());
1045     Bldr.generateNode(PP, State, Pred);
1046     return;
1047   }
1048 
1049   ExplodedNodeSet CleanDtorState;
1050   StmtNodeBuilder StmtBldr(Pred, CleanDtorState, *currBldrCtx);
1051   StmtBldr.generateNode(D.getBindTemporaryExpr(), Pred, State);
1052 
1053   QualType T = D.getBindTemporaryExpr()->getSubExpr()->getType();
1054   // FIXME: Currently CleanDtorState can be empty here due to temporaries being
1055   // bound to default parameters.
1056   assert(CleanDtorState.size() <= 1);
1057   ExplodedNode *CleanPred =
1058       CleanDtorState.empty() ? Pred : *CleanDtorState.begin();
1059 
1060   EvalCallOptions CallOpts;
1061   CallOpts.IsTemporaryCtorOrDtor = true;
1062   if (!MR) {
1063     CallOpts.IsCtorOrDtorWithImproperlyModeledTargetRegion = true;
1064 
1065     // If we have no MR, we still need to unwrap the array to avoid destroying
1066     // the whole array at once. Regardless, we'd eventually need to model array
1067     // destructors properly, element-by-element.
1068     while (const ArrayType *AT = getContext().getAsArrayType(T)) {
1069       T = AT->getElementType();
1070       CallOpts.IsArrayCtorOrDtor = true;
1071     }
1072   } else {
1073     // We'd eventually need to makeZeroElementRegion() trick here,
1074     // but for now we don't have the respective construction contexts,
1075     // so MR would always be null in this case. Do nothing for now.
1076   }
1077   VisitCXXDestructor(T, MR, D.getBindTemporaryExpr(),
1078                      /*IsBase=*/false, CleanPred, Dst, CallOpts);
1079 }
1080 
1081 void ExprEngine::processCleanupTemporaryBranch(const CXXBindTemporaryExpr *BTE,
1082                                                NodeBuilderContext &BldCtx,
1083                                                ExplodedNode *Pred,
1084                                                ExplodedNodeSet &Dst,
1085                                                const CFGBlock *DstT,
1086                                                const CFGBlock *DstF) {
1087   BranchNodeBuilder TempDtorBuilder(Pred, Dst, BldCtx, DstT, DstF);
1088   ProgramStateRef State = Pred->getState();
1089   const LocationContext *LC = Pred->getLocationContext();
1090   if (getObjectUnderConstruction(State, BTE, LC)) {
1091     TempDtorBuilder.markInfeasible(false);
1092     TempDtorBuilder.generateNode(State, true, Pred);
1093   } else {
1094     TempDtorBuilder.markInfeasible(true);
1095     TempDtorBuilder.generateNode(State, false, Pred);
1096   }
1097 }
1098 
1099 void ExprEngine::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE,
1100                                            ExplodedNodeSet &PreVisit,
1101                                            ExplodedNodeSet &Dst) {
1102   // This is a fallback solution in case we didn't have a construction
1103   // context when we were constructing the temporary. Otherwise the map should
1104   // have been populated there.
1105   if (!getAnalysisManager().options.includeTemporaryDtorsInCFG()) {
1106     // In case we don't have temporary destructors in the CFG, do not mark
1107     // the initialization - we would otherwise never clean it up.
1108     Dst = PreVisit;
1109     return;
1110   }
1111   StmtNodeBuilder StmtBldr(PreVisit, Dst, *currBldrCtx);
1112   for (ExplodedNode *Node : PreVisit) {
1113     ProgramStateRef State = Node->getState();
1114     const LocationContext *LC = Node->getLocationContext();
1115     if (!getObjectUnderConstruction(State, BTE, LC)) {
1116       // FIXME: Currently the state might also already contain the marker due to
1117       // incorrect handling of temporaries bound to default parameters; for
1118       // those, we currently skip the CXXBindTemporaryExpr but rely on adding
1119       // temporary destructor nodes.
1120       State = addObjectUnderConstruction(State, BTE, LC, UnknownVal());
1121     }
1122     StmtBldr.generateNode(BTE, Node, State);
1123   }
1124 }
1125 
1126 ProgramStateRef ExprEngine::escapeValue(ProgramStateRef State, SVal V,
1127                                         PointerEscapeKind K) const {
1128   class CollectReachableSymbolsCallback final : public SymbolVisitor {
1129     InvalidatedSymbols Symbols;
1130 
1131   public:
1132     explicit CollectReachableSymbolsCallback(ProgramStateRef) {}
1133 
1134     const InvalidatedSymbols &getSymbols() const { return Symbols; }
1135 
1136     bool VisitSymbol(SymbolRef Sym) override {
1137       Symbols.insert(Sym);
1138       return true;
1139     }
1140   };
1141 
1142   const CollectReachableSymbolsCallback &Scanner =
1143       State->scanReachableSymbols<CollectReachableSymbolsCallback>(V);
1144   return getCheckerManager().runCheckersForPointerEscape(
1145       State, Scanner.getSymbols(), /*CallEvent*/ nullptr, K, nullptr);
1146 }
1147 
1148 void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
1149                        ExplodedNodeSet &DstTop) {
1150   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
1151                                 S->getBeginLoc(), "Error evaluating statement");
1152   ExplodedNodeSet Dst;
1153   StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
1154 
1155   assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
1156 
1157   switch (S->getStmtClass()) {
1158     // C++, OpenMP and ARC stuff we don't support yet.
1159     case Expr::ObjCIndirectCopyRestoreExprClass:
1160     case Stmt::CXXDependentScopeMemberExprClass:
1161     case Stmt::CXXInheritedCtorInitExprClass:
1162     case Stmt::CXXTryStmtClass:
1163     case Stmt::CXXTypeidExprClass:
1164     case Stmt::CXXUuidofExprClass:
1165     case Stmt::CXXFoldExprClass:
1166     case Stmt::MSPropertyRefExprClass:
1167     case Stmt::MSPropertySubscriptExprClass:
1168     case Stmt::CXXUnresolvedConstructExprClass:
1169     case Stmt::DependentScopeDeclRefExprClass:
1170     case Stmt::ArrayTypeTraitExprClass:
1171     case Stmt::ExpressionTraitExprClass:
1172     case Stmt::UnresolvedLookupExprClass:
1173     case Stmt::UnresolvedMemberExprClass:
1174     case Stmt::TypoExprClass:
1175     case Stmt::CXXNoexceptExprClass:
1176     case Stmt::PackExpansionExprClass:
1177     case Stmt::SubstNonTypeTemplateParmPackExprClass:
1178     case Stmt::FunctionParmPackExprClass:
1179     case Stmt::CoroutineBodyStmtClass:
1180     case Stmt::CoawaitExprClass:
1181     case Stmt::DependentCoawaitExprClass:
1182     case Stmt::CoreturnStmtClass:
1183     case Stmt::CoyieldExprClass:
1184     case Stmt::SEHTryStmtClass:
1185     case Stmt::SEHExceptStmtClass:
1186     case Stmt::SEHLeaveStmtClass:
1187     case Stmt::SEHFinallyStmtClass:
1188     case Stmt::OMPParallelDirectiveClass:
1189     case Stmt::OMPSimdDirectiveClass:
1190     case Stmt::OMPForDirectiveClass:
1191     case Stmt::OMPForSimdDirectiveClass:
1192     case Stmt::OMPSectionsDirectiveClass:
1193     case Stmt::OMPSectionDirectiveClass:
1194     case Stmt::OMPSingleDirectiveClass:
1195     case Stmt::OMPMasterDirectiveClass:
1196     case Stmt::OMPCriticalDirectiveClass:
1197     case Stmt::OMPParallelForDirectiveClass:
1198     case Stmt::OMPParallelForSimdDirectiveClass:
1199     case Stmt::OMPParallelSectionsDirectiveClass:
1200     case Stmt::OMPTaskDirectiveClass:
1201     case Stmt::OMPTaskyieldDirectiveClass:
1202     case Stmt::OMPBarrierDirectiveClass:
1203     case Stmt::OMPTaskwaitDirectiveClass:
1204     case Stmt::OMPTaskgroupDirectiveClass:
1205     case Stmt::OMPFlushDirectiveClass:
1206     case Stmt::OMPOrderedDirectiveClass:
1207     case Stmt::OMPAtomicDirectiveClass:
1208     case Stmt::OMPTargetDirectiveClass:
1209     case Stmt::OMPTargetDataDirectiveClass:
1210     case Stmt::OMPTargetEnterDataDirectiveClass:
1211     case Stmt::OMPTargetExitDataDirectiveClass:
1212     case Stmt::OMPTargetParallelDirectiveClass:
1213     case Stmt::OMPTargetParallelForDirectiveClass:
1214     case Stmt::OMPTargetUpdateDirectiveClass:
1215     case Stmt::OMPTeamsDirectiveClass:
1216     case Stmt::OMPCancellationPointDirectiveClass:
1217     case Stmt::OMPCancelDirectiveClass:
1218     case Stmt::OMPTaskLoopDirectiveClass:
1219     case Stmt::OMPTaskLoopSimdDirectiveClass:
1220     case Stmt::OMPDistributeDirectiveClass:
1221     case Stmt::OMPDistributeParallelForDirectiveClass:
1222     case Stmt::OMPDistributeParallelForSimdDirectiveClass:
1223     case Stmt::OMPDistributeSimdDirectiveClass:
1224     case Stmt::OMPTargetParallelForSimdDirectiveClass:
1225     case Stmt::OMPTargetSimdDirectiveClass:
1226     case Stmt::OMPTeamsDistributeDirectiveClass:
1227     case Stmt::OMPTeamsDistributeSimdDirectiveClass:
1228     case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass:
1229     case Stmt::OMPTeamsDistributeParallelForDirectiveClass:
1230     case Stmt::OMPTargetTeamsDirectiveClass:
1231     case Stmt::OMPTargetTeamsDistributeDirectiveClass:
1232     case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
1233     case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
1234     case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
1235     case Stmt::CapturedStmtClass: {
1236       const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
1237       Engine.addAbortedBlock(node, currBldrCtx->getBlock());
1238       break;
1239     }
1240 
1241     case Stmt::ParenExprClass:
1242       llvm_unreachable("ParenExprs already handled.");
1243     case Stmt::GenericSelectionExprClass:
1244       llvm_unreachable("GenericSelectionExprs already handled.");
1245     // Cases that should never be evaluated simply because they shouldn't
1246     // appear in the CFG.
1247     case Stmt::BreakStmtClass:
1248     case Stmt::CaseStmtClass:
1249     case Stmt::CompoundStmtClass:
1250     case Stmt::ContinueStmtClass:
1251     case Stmt::CXXForRangeStmtClass:
1252     case Stmt::DefaultStmtClass:
1253     case Stmt::DoStmtClass:
1254     case Stmt::ForStmtClass:
1255     case Stmt::GotoStmtClass:
1256     case Stmt::IfStmtClass:
1257     case Stmt::IndirectGotoStmtClass:
1258     case Stmt::LabelStmtClass:
1259     case Stmt::NoStmtClass:
1260     case Stmt::NullStmtClass:
1261     case Stmt::SwitchStmtClass:
1262     case Stmt::WhileStmtClass:
1263     case Expr::MSDependentExistsStmtClass:
1264       llvm_unreachable("Stmt should not be in analyzer evaluation loop");
1265 
1266     case Stmt::ObjCSubscriptRefExprClass:
1267     case Stmt::ObjCPropertyRefExprClass:
1268       llvm_unreachable("These are handled by PseudoObjectExpr");
1269 
1270     case Expr::ConstantExprClass:
1271       return Visit(cast<ConstantExpr>(S)->getSubExpr(), Pred, DstTop);
1272 
1273     case Stmt::GNUNullExprClass: {
1274       // GNU __null is a pointer-width integer, not an actual pointer.
1275       ProgramStateRef state = Pred->getState();
1276       state = state->BindExpr(S, Pred->getLocationContext(),
1277                               svalBuilder.makeIntValWithPtrWidth(0, false));
1278       Bldr.generateNode(S, Pred, state);
1279       break;
1280     }
1281 
1282     case Stmt::ObjCAtSynchronizedStmtClass:
1283       Bldr.takeNodes(Pred);
1284       VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
1285       Bldr.addNodes(Dst);
1286       break;
1287 
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 three possible cases:
2627 // (1) We are binding to something that is not a memory region.
2628 // (2) We are binding to a MemrRegion that does not have stack storage.
2629 // (3) We are binding to a MemRegion with stack storage that the store
2630 //     does not understand.
2631 ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
2632                                                         SVal Loc,
2633                                                         SVal Val,
2634                                                         const LocationContext *LCtx) {
2635   // Are we storing to something that causes the value to "escape"?
2636   bool escapes = true;
2637 
2638   // TODO: Move to StoreManager.
2639   if (Optional<loc::MemRegionVal> regionLoc = Loc.getAs<loc::MemRegionVal>()) {
2640     escapes = !regionLoc->getRegion()->hasStackStorage();
2641 
2642     if (!escapes) {
2643       // To test (3), generate a new state with the binding added.  If it is
2644       // the same state, then it escapes (since the store cannot represent
2645       // the binding).
2646       // Do this only if we know that the store is not supposed to generate the
2647       // same state.
2648       SVal StoredVal = State->getSVal(regionLoc->getRegion());
2649       if (StoredVal != Val)
2650         escapes = (State == (State->bindLoc(*regionLoc, Val, LCtx)));
2651     }
2652   }
2653 
2654   // If our store can represent the binding and we aren't storing to something
2655   // that doesn't have local storage then just return and have the simulation
2656   // state continue as is.
2657   if (!escapes)
2658     return State;
2659 
2660   // Otherwise, find all symbols referenced by 'val' that we are tracking
2661   // and stop tracking them.
2662   State = escapeValue(State, Val, PSK_EscapeOnBind);
2663   return State;
2664 }
2665 
2666 ProgramStateRef
2667 ExprEngine::notifyCheckersOfPointerEscape(ProgramStateRef State,
2668     const InvalidatedSymbols *Invalidated,
2669     ArrayRef<const MemRegion *> ExplicitRegions,
2670     const CallEvent *Call,
2671     RegionAndSymbolInvalidationTraits &ITraits) {
2672   if (!Invalidated || Invalidated->empty())
2673     return State;
2674 
2675   if (!Call)
2676     return getCheckerManager().runCheckersForPointerEscape(State,
2677                                                            *Invalidated,
2678                                                            nullptr,
2679                                                            PSK_EscapeOther,
2680                                                            &ITraits);
2681 
2682   // If the symbols were invalidated by a call, we want to find out which ones
2683   // were invalidated directly due to being arguments to the call.
2684   InvalidatedSymbols SymbolsDirectlyInvalidated;
2685   for (const auto I : ExplicitRegions) {
2686     if (const SymbolicRegion *R = I->StripCasts()->getAs<SymbolicRegion>())
2687       SymbolsDirectlyInvalidated.insert(R->getSymbol());
2688   }
2689 
2690   InvalidatedSymbols SymbolsIndirectlyInvalidated;
2691   for (const auto &sym : *Invalidated) {
2692     if (SymbolsDirectlyInvalidated.count(sym))
2693       continue;
2694     SymbolsIndirectlyInvalidated.insert(sym);
2695   }
2696 
2697   if (!SymbolsDirectlyInvalidated.empty())
2698     State = getCheckerManager().runCheckersForPointerEscape(State,
2699         SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall, &ITraits);
2700 
2701   // Notify about the symbols that get indirectly invalidated by the call.
2702   if (!SymbolsIndirectlyInvalidated.empty())
2703     State = getCheckerManager().runCheckersForPointerEscape(State,
2704         SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall, &ITraits);
2705 
2706   return State;
2707 }
2708 
2709 /// evalBind - Handle the semantics of binding a value to a specific location.
2710 ///  This method is used by evalStore and (soon) VisitDeclStmt, and others.
2711 void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
2712                           ExplodedNode *Pred,
2713                           SVal location, SVal Val,
2714                           bool atDeclInit, const ProgramPoint *PP) {
2715   const LocationContext *LC = Pred->getLocationContext();
2716   PostStmt PS(StoreE, LC);
2717   if (!PP)
2718     PP = &PS;
2719 
2720   // Do a previsit of the bind.
2721   ExplodedNodeSet CheckedSet;
2722   getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
2723                                          StoreE, *this, *PP);
2724 
2725   StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
2726 
2727   // If the location is not a 'Loc', it will already be handled by
2728   // the checkers.  There is nothing left to do.
2729   if (!location.getAs<Loc>()) {
2730     const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/nullptr,
2731                                      /*tag*/nullptr);
2732     ProgramStateRef state = Pred->getState();
2733     state = processPointerEscapedOnBind(state, location, Val, LC);
2734     Bldr.generateNode(L, state, Pred);
2735     return;
2736   }
2737 
2738   for (const auto PredI : CheckedSet) {
2739     ProgramStateRef state = PredI->getState();
2740 
2741     state = processPointerEscapedOnBind(state, location, Val, LC);
2742 
2743     // When binding the value, pass on the hint that this is a initialization.
2744     // For initializations, we do not need to inform clients of region
2745     // changes.
2746     state = state->bindLoc(location.castAs<Loc>(),
2747                            Val, LC, /* notifyChanges = */ !atDeclInit);
2748 
2749     const MemRegion *LocReg = nullptr;
2750     if (Optional<loc::MemRegionVal> LocRegVal =
2751             location.getAs<loc::MemRegionVal>()) {
2752       LocReg = LocRegVal->getRegion();
2753     }
2754 
2755     const ProgramPoint L = PostStore(StoreE, LC, LocReg, nullptr);
2756     Bldr.generateNode(L, state, PredI);
2757   }
2758 }
2759 
2760 /// evalStore - Handle the semantics of a store via an assignment.
2761 ///  @param Dst The node set to store generated state nodes
2762 ///  @param AssignE The assignment expression if the store happens in an
2763 ///         assignment.
2764 ///  @param LocationE The location expression that is stored to.
2765 ///  @param state The current simulation state
2766 ///  @param location The location to store the value
2767 ///  @param Val The value to be stored
2768 void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
2769                              const Expr *LocationE,
2770                              ExplodedNode *Pred,
2771                              ProgramStateRef state, SVal location, SVal Val,
2772                              const ProgramPointTag *tag) {
2773   // Proceed with the store.  We use AssignE as the anchor for the PostStore
2774   // ProgramPoint if it is non-NULL, and LocationE otherwise.
2775   const Expr *StoreE = AssignE ? AssignE : LocationE;
2776 
2777   // Evaluate the location (checks for bad dereferences).
2778   ExplodedNodeSet Tmp;
2779   evalLocation(Tmp, AssignE, LocationE, Pred, state, location, false);
2780 
2781   if (Tmp.empty())
2782     return;
2783 
2784   if (location.isUndef())
2785     return;
2786 
2787   for (const auto I : Tmp)
2788     evalBind(Dst, StoreE, I, location, Val, false);
2789 }
2790 
2791 void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
2792                           const Expr *NodeEx,
2793                           const Expr *BoundEx,
2794                           ExplodedNode *Pred,
2795                           ProgramStateRef state,
2796                           SVal location,
2797                           const ProgramPointTag *tag,
2798                           QualType LoadTy) {
2799   assert(!location.getAs<NonLoc>() && "location cannot be a NonLoc.");
2800   assert(NodeEx);
2801   assert(BoundEx);
2802   // Evaluate the location (checks for bad dereferences).
2803   ExplodedNodeSet Tmp;
2804   evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, true);
2805   if (Tmp.empty())
2806     return;
2807 
2808   StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
2809   if (location.isUndef())
2810     return;
2811 
2812   // Proceed with the load.
2813   for (const auto I : Tmp) {
2814     state = I->getState();
2815     const LocationContext *LCtx = I->getLocationContext();
2816 
2817     SVal V = UnknownVal();
2818     if (location.isValid()) {
2819       if (LoadTy.isNull())
2820         LoadTy = BoundEx->getType();
2821       V = state->getSVal(location.castAs<Loc>(), LoadTy);
2822     }
2823 
2824     Bldr.generateNode(NodeEx, I, state->BindExpr(BoundEx, LCtx, V), tag,
2825                       ProgramPoint::PostLoadKind);
2826   }
2827 }
2828 
2829 void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
2830                               const Stmt *NodeEx,
2831                               const Stmt *BoundEx,
2832                               ExplodedNode *Pred,
2833                               ProgramStateRef state,
2834                               SVal location,
2835                               bool isLoad) {
2836   StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
2837   // Early checks for performance reason.
2838   if (location.isUnknown()) {
2839     return;
2840   }
2841 
2842   ExplodedNodeSet Src;
2843   BldrTop.takeNodes(Pred);
2844   StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
2845   if (Pred->getState() != state) {
2846     // Associate this new state with an ExplodedNode.
2847     // FIXME: If I pass null tag, the graph is incorrect, e.g for
2848     //   int *p;
2849     //   p = 0;
2850     //   *p = 0xDEADBEEF;
2851     // "p = 0" is not noted as "Null pointer value stored to 'p'" but
2852     // instead "int *p" is noted as
2853     // "Variable 'p' initialized to a null pointer value"
2854 
2855     static SimpleProgramPointTag tag(TagProviderName, "Location");
2856     Bldr.generateNode(NodeEx, Pred, state, &tag);
2857   }
2858   ExplodedNodeSet Tmp;
2859   getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
2860                                              NodeEx, BoundEx, *this);
2861   BldrTop.addNodes(Tmp);
2862 }
2863 
2864 std::pair<const ProgramPointTag *, const ProgramPointTag*>
2865 ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
2866   static SimpleProgramPointTag
2867          eagerlyAssumeBinOpBifurcationTrue(TagProviderName,
2868                                            "Eagerly Assume True"),
2869          eagerlyAssumeBinOpBifurcationFalse(TagProviderName,
2870                                             "Eagerly Assume False");
2871   return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
2872                         &eagerlyAssumeBinOpBifurcationFalse);
2873 }
2874 
2875 void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
2876                                                    ExplodedNodeSet &Src,
2877                                                    const Expr *Ex) {
2878   StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
2879 
2880   for (const auto Pred : Src) {
2881     // Test if the previous node was as the same expression.  This can happen
2882     // when the expression fails to evaluate to anything meaningful and
2883     // (as an optimization) we don't generate a node.
2884     ProgramPoint P = Pred->getLocation();
2885     if (!P.getAs<PostStmt>() || P.castAs<PostStmt>().getStmt() != Ex) {
2886       continue;
2887     }
2888 
2889     ProgramStateRef state = Pred->getState();
2890     SVal V = state->getSVal(Ex, Pred->getLocationContext());
2891     Optional<nonloc::SymbolVal> SEV = V.getAs<nonloc::SymbolVal>();
2892     if (SEV && SEV->isExpression()) {
2893       const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
2894         geteagerlyAssumeBinOpBifurcationTags();
2895 
2896       ProgramStateRef StateTrue, StateFalse;
2897       std::tie(StateTrue, StateFalse) = state->assume(*SEV);
2898 
2899       // First assume that the condition is true.
2900       if (StateTrue) {
2901         SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
2902         StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
2903         Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
2904       }
2905 
2906       // Next, assume that the condition is false.
2907       if (StateFalse) {
2908         SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
2909         StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
2910         Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
2911       }
2912     }
2913   }
2914 }
2915 
2916 void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
2917                                  ExplodedNodeSet &Dst) {
2918   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2919   // We have processed both the inputs and the outputs.  All of the outputs
2920   // should evaluate to Locs.  Nuke all of their values.
2921 
2922   // FIXME: Some day in the future it would be nice to allow a "plug-in"
2923   // which interprets the inline asm and stores proper results in the
2924   // outputs.
2925 
2926   ProgramStateRef state = Pred->getState();
2927 
2928   for (const Expr *O : A->outputs()) {
2929     SVal X = state->getSVal(O, Pred->getLocationContext());
2930     assert(!X.getAs<NonLoc>());  // Should be an Lval, or unknown, undef.
2931 
2932     if (Optional<Loc> LV = X.getAs<Loc>())
2933       state = state->bindLoc(*LV, UnknownVal(), Pred->getLocationContext());
2934   }
2935 
2936   Bldr.generateNode(A, Pred, state);
2937 }
2938 
2939 void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
2940                                 ExplodedNodeSet &Dst) {
2941   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
2942   Bldr.generateNode(A, Pred, Pred->getState());
2943 }
2944 
2945 //===----------------------------------------------------------------------===//
2946 // Visualization.
2947 //===----------------------------------------------------------------------===//
2948 
2949 #ifndef NDEBUG
2950 namespace llvm {
2951 
2952 template<>
2953 struct DOTGraphTraits<ExplodedGraph*> : public DefaultDOTGraphTraits {
2954   DOTGraphTraits (bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2955 
2956   static bool nodeHasBugReport(const ExplodedNode *N) {
2957     BugReporter &BR = static_cast<ExprEngine *>(
2958       N->getState()->getStateManager().getOwningEngine())->getBugReporter();
2959 
2960     const auto EQClasses =
2961         llvm::make_range(BR.EQClasses_begin(), BR.EQClasses_end());
2962 
2963     for (const auto &EQ : EQClasses) {
2964       for (const BugReport &Report : EQ) {
2965         if (Report.getErrorNode() == N)
2966           return true;
2967       }
2968     }
2969     return false;
2970   }
2971 
2972   /// \p PreCallback: callback before break.
2973   /// \p PostCallback: callback after break.
2974   /// \p Stop: stop iteration if returns {@code true}
2975   /// \return Whether {@code Stop} ever returned {@code true}.
2976   static bool traverseHiddenNodes(
2977       const ExplodedNode *N,
2978       llvm::function_ref<void(const ExplodedNode *)> PreCallback,
2979       llvm::function_ref<void(const ExplodedNode *)> PostCallback,
2980       llvm::function_ref<bool(const ExplodedNode *)> Stop) {
2981     const ExplodedNode *FirstHiddenNode = N;
2982     while (FirstHiddenNode->pred_size() == 1 &&
2983            isNodeHidden(*FirstHiddenNode->pred_begin())) {
2984       FirstHiddenNode = *FirstHiddenNode->pred_begin();
2985     }
2986     const ExplodedNode *OtherNode = FirstHiddenNode;
2987     while (true) {
2988       PreCallback(OtherNode);
2989       if (Stop(OtherNode))
2990         return true;
2991 
2992       if (OtherNode == N)
2993         break;
2994       PostCallback(OtherNode);
2995 
2996       OtherNode = *OtherNode->succ_begin();
2997     }
2998     return false;
2999   }
3000 
3001   static std::string getNodeAttributes(const ExplodedNode *N,
3002                                        ExplodedGraph *) {
3003     SmallVector<StringRef, 10> Out;
3004     auto Noop = [](const ExplodedNode*){};
3005     if (traverseHiddenNodes(N, Noop, Noop, &nodeHasBugReport)) {
3006       Out.push_back("style=filled");
3007       Out.push_back("fillcolor=red");
3008     }
3009 
3010     if (traverseHiddenNodes(N, Noop, Noop,
3011                             [](const ExplodedNode *C) { return C->isSink(); }))
3012       Out.push_back("color=blue");
3013     return llvm::join(Out, ",");
3014   }
3015 
3016   static bool isNodeHidden(const ExplodedNode *N) {
3017     return N->isTrivial();
3018   }
3019 
3020   static std::string getNodeLabel(const ExplodedNode *N, ExplodedGraph *G){
3021     std::string sbuf;
3022     llvm::raw_string_ostream Out(sbuf);
3023 
3024     ProgramStateRef State = N->getState();
3025 
3026     // Dump program point for all the previously skipped nodes.
3027     traverseHiddenNodes(
3028         N,
3029         [&](const ExplodedNode *OtherNode) {
3030           OtherNode->getLocation().print(/*CR=*/"\\l", Out);
3031           if (const ProgramPointTag *Tag = OtherNode->getLocation().getTag())
3032             Out << "\\lTag:" << Tag->getTagDescription();
3033           if (N->isSink())
3034             Out << "\\lNode is sink\\l";
3035           if (nodeHasBugReport(N))
3036             Out << "\\lBug report attached\\l";
3037         },
3038         [&](const ExplodedNode *) { Out << "\\l--------\\l"; },
3039         [&](const ExplodedNode *) { return false; });
3040 
3041     Out << "\\l\\|";
3042 
3043     Out << "StateID: ST" << State->getID() << ", NodeID: N" << N->getID(G)
3044         << " <" << (const void *)N << ">\\|";
3045 
3046     bool SameAsAllPredecessors =
3047         std::all_of(N->pred_begin(), N->pred_end(), [&](const ExplodedNode *P) {
3048           return P->getState() == State;
3049         });
3050     if (!SameAsAllPredecessors)
3051       State->printDOT(Out, N->getLocationContext());
3052     return Out.str();
3053   }
3054 };
3055 
3056 } // namespace llvm
3057 #endif
3058 
3059 void ExprEngine::ViewGraph(bool trim) {
3060 #ifndef NDEBUG
3061   std::string Filename = DumpGraph(trim);
3062   llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
3063 #endif
3064   llvm::errs() << "Warning: viewing graph requires assertions" << "\n";
3065 }
3066 
3067 
3068 void ExprEngine::ViewGraph(ArrayRef<const ExplodedNode*> Nodes) {
3069 #ifndef NDEBUG
3070   std::string Filename = DumpGraph(Nodes);
3071   llvm::DisplayGraph(Filename, false, llvm::GraphProgram::DOT);
3072 #endif
3073   llvm::errs() << "Warning: viewing graph requires assertions" << "\n";
3074 }
3075 
3076 std::string ExprEngine::DumpGraph(bool trim, StringRef Filename) {
3077 #ifndef NDEBUG
3078   if (trim) {
3079     std::vector<const ExplodedNode *> Src;
3080 
3081     // Iterate through the reports and get their nodes.
3082     for (BugReporter::EQClasses_iterator
3083            EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
3084       const auto *N = const_cast<ExplodedNode *>(EI->begin()->getErrorNode());
3085       if (N) Src.push_back(N);
3086     }
3087     return DumpGraph(Src, Filename);
3088   } else {
3089     return llvm::WriteGraph(&G, "ExprEngine", /*ShortNames=*/false,
3090                      /*Title=*/"Exploded Graph", /*Filename=*/Filename);
3091   }
3092 #endif
3093   llvm::errs() << "Warning: dumping graph requires assertions" << "\n";
3094   return "";
3095 }
3096 
3097 std::string ExprEngine::DumpGraph(ArrayRef<const ExplodedNode*> Nodes,
3098                                   StringRef Filename) {
3099 #ifndef NDEBUG
3100   std::unique_ptr<ExplodedGraph> TrimmedG(G.trim(Nodes));
3101 
3102   if (!TrimmedG.get()) {
3103     llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
3104   } else {
3105     return llvm::WriteGraph(TrimmedG.get(), "TrimmedExprEngine",
3106                             /*ShortNames=*/false,
3107                             /*Title=*/"Trimmed Exploded Graph",
3108                             /*Filename=*/Filename);
3109   }
3110 #endif
3111   llvm::errs() << "Warning: dumping graph requires assertions" << "\n";
3112   return "";
3113 }
3114 
3115 void *ProgramStateTrait<ReplayWithoutInlining>::GDMIndex() {
3116   static int index = 0;
3117   return &index;
3118 }
3119