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