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