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