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