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