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