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/CheckerManager.h"
17 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
18 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngineBuilders.h"
21 #include "clang/AST/CharUnits.h"
22 #include "clang/AST/ParentMap.h"
23 #include "clang/AST/StmtObjC.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/Basic/Builtins.h"
26 #include "clang/Basic/SourceManager.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/PrettyStackTrace.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/ADT/ImmutableList.h"
31 
32 #ifndef NDEBUG
33 #include "llvm/Support/GraphWriter.h"
34 #endif
35 
36 using namespace clang;
37 using namespace ento;
38 using llvm::dyn_cast;
39 using llvm::dyn_cast_or_null;
40 using llvm::cast;
41 using llvm::APSInt;
42 
43 namespace {
44   // Trait class for recording returned expression in the state.
45   struct ReturnExpr {
46     static int TagInt;
47     typedef const Stmt *data_type;
48   };
49   int ReturnExpr::TagInt;
50 }
51 
52 //===----------------------------------------------------------------------===//
53 // Utility functions.
54 //===----------------------------------------------------------------------===//
55 
56 static inline Selector GetNullarySelector(const char* name, ASTContext& Ctx) {
57   IdentifierInfo* II = &Ctx.Idents.get(name);
58   return Ctx.Selectors.getSelector(0, &II);
59 }
60 
61 //===----------------------------------------------------------------------===//
62 // Engine construction and deletion.
63 //===----------------------------------------------------------------------===//
64 
65 ExprEngine::ExprEngine(AnalysisManager &mgr, TransferFuncs *tf)
66   : AMgr(mgr),
67     Engine(*this),
68     G(Engine.getGraph()),
69     Builder(NULL),
70     StateMgr(getContext(), mgr.getStoreManagerCreator(),
71              mgr.getConstraintManagerCreator(), G.getAllocator(),
72              *this),
73     SymMgr(StateMgr.getSymbolManager()),
74     svalBuilder(StateMgr.getSValBuilder()),
75     EntryNode(NULL), currentStmt(NULL),
76     NSExceptionII(NULL), NSExceptionInstanceRaiseSelectors(NULL),
77     RaiseSel(GetNullarySelector("raise", getContext())),
78     BR(mgr, *this), TF(tf) {
79 
80   // FIXME: Eventually remove the TF object entirely.
81   TF->RegisterChecks(*this);
82   TF->RegisterPrinters(getStateManager().Printers);
83 
84   if (mgr.shouldEagerlyTrimExplodedGraph()) {
85     // Enable eager node reclaimation when constructing the ExplodedGraph.
86     G.enableNodeReclamation();
87   }
88 }
89 
90 ExprEngine::~ExprEngine() {
91   BR.FlushReports();
92   delete [] NSExceptionInstanceRaiseSelectors;
93 }
94 
95 //===----------------------------------------------------------------------===//
96 // Utility methods.
97 //===----------------------------------------------------------------------===//
98 
99 const GRState* ExprEngine::getInitialState(const LocationContext *InitLoc) {
100   const GRState *state = StateMgr.getInitialState(InitLoc);
101 
102   // Preconditions.
103 
104   // FIXME: It would be nice if we had a more general mechanism to add
105   // such preconditions.  Some day.
106   do {
107     const Decl *D = InitLoc->getDecl();
108     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
109       // Precondition: the first argument of 'main' is an integer guaranteed
110       //  to be > 0.
111       const IdentifierInfo *II = FD->getIdentifier();
112       if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
113         break;
114 
115       const ParmVarDecl *PD = FD->getParamDecl(0);
116       QualType T = PD->getType();
117       if (!T->isIntegerType())
118         break;
119 
120       const MemRegion *R = state->getRegion(PD, InitLoc);
121       if (!R)
122         break;
123 
124       SVal V = state->getSVal(loc::MemRegionVal(R));
125       SVal Constraint_untested = evalBinOp(state, BO_GT, V,
126                                            svalBuilder.makeZeroVal(T),
127                                            getContext().IntTy);
128 
129       DefinedOrUnknownSVal *Constraint =
130         dyn_cast<DefinedOrUnknownSVal>(&Constraint_untested);
131 
132       if (!Constraint)
133         break;
134 
135       if (const GRState *newState = state->assume(*Constraint, true))
136         state = newState;
137 
138       break;
139     }
140 
141     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
142       // Precondition: 'self' is always non-null upon entry to an Objective-C
143       // method.
144       const ImplicitParamDecl *SelfD = MD->getSelfDecl();
145       const MemRegion *R = state->getRegion(SelfD, InitLoc);
146       SVal V = state->getSVal(loc::MemRegionVal(R));
147 
148       if (const Loc *LV = dyn_cast<Loc>(&V)) {
149         // Assume that the pointer value in 'self' is non-null.
150         state = state->assume(*LV, true);
151         assert(state && "'self' cannot be null");
152       }
153     }
154   } while (0);
155 
156   return state;
157 }
158 
159 bool
160 ExprEngine::doesInvalidateGlobals(const CallOrObjCMessage &callOrMessage) const
161 {
162   if (callOrMessage.isFunctionCall() && !callOrMessage.isCXXCall()) {
163     SVal calleeV = callOrMessage.getFunctionCallee();
164     if (const FunctionTextRegion *codeR =
165           llvm::dyn_cast_or_null<FunctionTextRegion>(calleeV.getAsRegion())) {
166 
167       const FunctionDecl *fd = codeR->getDecl();
168       if (const IdentifierInfo *ii = fd->getIdentifier()) {
169         llvm::StringRef fname = ii->getName();
170         if (fname == "strlen")
171           return false;
172       }
173     }
174   }
175 
176   // The conservative answer: invalidates globals.
177   return true;
178 }
179 
180 //===----------------------------------------------------------------------===//
181 // Top-level transfer function logic (Dispatcher).
182 //===----------------------------------------------------------------------===//
183 
184 /// evalAssume - Called by ConstraintManager. Used to call checker-specific
185 ///  logic for handling assumptions on symbolic values.
186 const GRState *ExprEngine::processAssume(const GRState *state, SVal cond,
187                                            bool assumption) {
188   state = getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
189 
190   // If the state is infeasible at this point, bail out.
191   if (!state)
192     return NULL;
193 
194   return TF->evalAssume(state, cond, assumption);
195 }
196 
197 bool ExprEngine::wantsRegionChangeUpdate(const GRState* state) {
198   return getCheckerManager().wantsRegionChangeUpdate(state);
199 }
200 
201 const GRState *
202 ExprEngine::processRegionChanges(const GRState *state,
203                             const StoreManager::InvalidatedSymbols *invalidated,
204                                  const MemRegion * const *Begin,
205                                  const MemRegion * const *End) {
206   return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
207                                                          Begin, End);
208 }
209 
210 void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
211   getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
212 }
213 
214 void ExprEngine::processCFGElement(const CFGElement E,
215                                   StmtNodeBuilder& builder) {
216   switch (E.getKind()) {
217     case CFGElement::Invalid:
218       llvm_unreachable("Unexpected CFGElement kind.");
219     case CFGElement::Statement:
220       ProcessStmt(E.getAs<CFGStmt>()->getStmt(), builder);
221       return;
222     case CFGElement::Initializer:
223       ProcessInitializer(E.getAs<CFGInitializer>()->getInitializer(), builder);
224       return;
225     case CFGElement::AutomaticObjectDtor:
226     case CFGElement::BaseDtor:
227     case CFGElement::MemberDtor:
228     case CFGElement::TemporaryDtor:
229       ProcessImplicitDtor(*E.getAs<CFGImplicitDtor>(), builder);
230       return;
231   }
232 }
233 
234 void ExprEngine::ProcessStmt(const CFGStmt S, StmtNodeBuilder& builder) {
235   // Reclaim any unnecessary nodes in the ExplodedGraph.
236   G.reclaimRecentlyAllocatedNodes();
237   // Recycle any unused states in the GRStateManager.
238   StateMgr.recycleUnusedStates();
239 
240   currentStmt = S.getStmt();
241   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
242                                 currentStmt->getLocStart(),
243                                 "Error evaluating statement");
244 
245   Builder = &builder;
246   EntryNode = builder.getPredecessor();
247 
248   // Create the cleaned state.
249   const LocationContext *LC = EntryNode->getLocationContext();
250   SymbolReaper SymReaper(LC, currentStmt, SymMgr);
251 
252   if (AMgr.shouldPurgeDead()) {
253     const GRState *St = EntryNode->getState();
254     getCheckerManager().runCheckersForLiveSymbols(St, SymReaper);
255 
256     const StackFrameContext *SFC = LC->getCurrentStackFrame();
257     CleanedState = StateMgr.removeDeadBindings(St, SFC, SymReaper);
258   } else {
259     CleanedState = EntryNode->getState();
260   }
261 
262   // Process any special transfer function for dead symbols.
263   ExplodedNodeSet Tmp;
264 
265   if (!SymReaper.hasDeadSymbols())
266     Tmp.Add(EntryNode);
267   else {
268     SaveAndRestore<bool> OldSink(Builder->BuildSinks);
269     SaveOr OldHasGen(Builder->hasGeneratedNode);
270 
271     SaveAndRestore<bool> OldPurgeDeadSymbols(Builder->PurgingDeadSymbols);
272     Builder->PurgingDeadSymbols = true;
273 
274     // FIXME: This should soon be removed.
275     ExplodedNodeSet Tmp2;
276     getTF().evalDeadSymbols(Tmp2, *this, *Builder, EntryNode,
277                             CleanedState, SymReaper);
278 
279     getCheckerManager().runCheckersForDeadSymbols(Tmp, Tmp2,
280                                                  SymReaper, currentStmt, *this);
281 
282     if (!Builder->BuildSinks && !Builder->hasGeneratedNode)
283       Tmp.Add(EntryNode);
284   }
285 
286   bool HasAutoGenerated = false;
287 
288   for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
289     ExplodedNodeSet Dst;
290 
291     // Set the cleaned state.
292     Builder->SetCleanedState(*I == EntryNode ? CleanedState : GetState(*I));
293 
294     // Visit the statement.
295     Visit(currentStmt, *I, Dst);
296 
297     // Do we need to auto-generate a node?  We only need to do this to generate
298     // a node with a "cleaned" state; CoreEngine will actually handle
299     // auto-transitions for other cases.
300     if (Dst.size() == 1 && *Dst.begin() == EntryNode
301         && !Builder->hasGeneratedNode && !HasAutoGenerated) {
302       HasAutoGenerated = true;
303       builder.generateNode(currentStmt, GetState(EntryNode), *I);
304     }
305   }
306 
307   // NULL out these variables to cleanup.
308   CleanedState = NULL;
309   EntryNode = NULL;
310 
311   currentStmt = 0;
312 
313   Builder = NULL;
314 }
315 
316 void ExprEngine::ProcessInitializer(const CFGInitializer Init,
317                                     StmtNodeBuilder &builder) {
318   // We don't set EntryNode and currentStmt. And we don't clean up state.
319   const CXXCtorInitializer *BMI = Init.getInitializer();
320 
321   ExplodedNode *pred = builder.getPredecessor();
322 
323   const StackFrameContext *stackFrame = cast<StackFrameContext>(pred->getLocationContext());
324   const CXXConstructorDecl *decl = cast<CXXConstructorDecl>(stackFrame->getDecl());
325   const CXXThisRegion *thisReg = getCXXThisRegion(decl, stackFrame);
326 
327   SVal thisVal = pred->getState()->getSVal(thisReg);
328 
329   if (BMI->isAnyMemberInitializer()) {
330     ExplodedNodeSet Dst;
331 
332     // Evaluate the initializer.
333     Visit(BMI->getInit(), pred, Dst);
334 
335     for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end(); I != E; ++I){
336       ExplodedNode *Pred = *I;
337       const GRState *state = Pred->getState();
338 
339       const FieldDecl *FD = BMI->getAnyMember();
340 
341       SVal FieldLoc = state->getLValue(FD, thisVal);
342       SVal InitVal = state->getSVal(BMI->getInit());
343       state = state->bindLoc(FieldLoc, InitVal);
344 
345       // Use a custom node building process.
346       PostInitializer PP(BMI, stackFrame);
347       // Builder automatically add the generated node to the deferred set,
348       // which are processed in the builder's dtor.
349       builder.generateNode(PP, state, Pred);
350     }
351     return;
352   }
353 
354   assert(BMI->isBaseInitializer());
355 
356   // Get the base class declaration.
357   const CXXConstructExpr *ctorExpr = cast<CXXConstructExpr>(BMI->getInit());
358 
359   // Create the base object region.
360   SVal baseVal =
361     getStoreManager().evalDerivedToBase(thisVal, ctorExpr->getType());
362   const MemRegion *baseReg = baseVal.getAsRegion();
363   assert(baseReg);
364   Builder = &builder;
365   ExplodedNodeSet dst;
366   VisitCXXConstructExpr(ctorExpr, baseReg, pred, dst);
367 }
368 
369 void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
370                                        StmtNodeBuilder &builder) {
371   Builder = &builder;
372 
373   switch (D.getKind()) {
374   case CFGElement::AutomaticObjectDtor:
375     ProcessAutomaticObjDtor(cast<CFGAutomaticObjDtor>(D), builder);
376     break;
377   case CFGElement::BaseDtor:
378     ProcessBaseDtor(cast<CFGBaseDtor>(D), builder);
379     break;
380   case CFGElement::MemberDtor:
381     ProcessMemberDtor(cast<CFGMemberDtor>(D), builder);
382     break;
383   case CFGElement::TemporaryDtor:
384     ProcessTemporaryDtor(cast<CFGTemporaryDtor>(D), builder);
385     break;
386   default:
387     llvm_unreachable("Unexpected dtor kind.");
388   }
389 }
390 
391 void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor dtor,
392                                            StmtNodeBuilder &builder) {
393   ExplodedNode *pred = builder.getPredecessor();
394   const GRState *state = pred->getState();
395   const VarDecl *varDecl = dtor.getVarDecl();
396 
397   QualType varType = varDecl->getType();
398 
399   if (const ReferenceType *refType = varType->getAs<ReferenceType>())
400     varType = refType->getPointeeType();
401 
402   const CXXRecordDecl *recordDecl = varType->getAsCXXRecordDecl();
403   assert(recordDecl && "get CXXRecordDecl fail");
404   const CXXDestructorDecl *dtorDecl = recordDecl->getDestructor();
405 
406   Loc dest = state->getLValue(varDecl, pred->getLocationContext());
407 
408   ExplodedNodeSet dstSet;
409   VisitCXXDestructor(dtorDecl, cast<loc::MemRegionVal>(dest).getRegion(),
410                      dtor.getTriggerStmt(), pred, dstSet);
411 }
412 
413 void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
414                                    StmtNodeBuilder &builder) {
415 }
416 
417 void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
418                                      StmtNodeBuilder &builder) {
419 }
420 
421 void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
422                                         StmtNodeBuilder &builder) {
423 }
424 
425 void ExprEngine::Visit(const Stmt* S, ExplodedNode* Pred,
426                          ExplodedNodeSet& Dst) {
427   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
428                                 S->getLocStart(),
429                                 "Error evaluating statement");
430 
431   // Expressions to ignore.
432   if (const Expr *Ex = dyn_cast<Expr>(S))
433     S = Ex->IgnoreParens();
434 
435   // FIXME: add metadata to the CFG so that we can disable
436   //  this check when we KNOW that there is no block-level subexpression.
437   //  The motivation is that this check requires a hashtable lookup.
438 
439   if (S != currentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(S)) {
440     Dst.Add(Pred);
441     return;
442   }
443 
444   switch (S->getStmtClass()) {
445     // C++ stuff we don't support yet.
446     case Stmt::CXXBindTemporaryExprClass:
447     case Stmt::CXXCatchStmtClass:
448     case Stmt::CXXDependentScopeMemberExprClass:
449     case Stmt::CXXForRangeStmtClass:
450     case Stmt::CXXPseudoDestructorExprClass:
451     case Stmt::CXXTemporaryObjectExprClass:
452     case Stmt::CXXThrowExprClass:
453     case Stmt::CXXTryStmtClass:
454     case Stmt::CXXTypeidExprClass:
455     case Stmt::CXXUuidofExprClass:
456     case Stmt::CXXUnresolvedConstructExprClass:
457     case Stmt::CXXScalarValueInitExprClass:
458     case Stmt::DependentScopeDeclRefExprClass:
459     case Stmt::UnaryTypeTraitExprClass:
460     case Stmt::BinaryTypeTraitExprClass:
461     case Stmt::ArrayTypeTraitExprClass:
462     case Stmt::ExpressionTraitExprClass:
463     case Stmt::UnresolvedLookupExprClass:
464     case Stmt::UnresolvedMemberExprClass:
465     case Stmt::CXXNoexceptExprClass:
466     case Stmt::PackExpansionExprClass:
467     case Stmt::SubstNonTypeTemplateParmPackExprClass:
468     case Stmt::SEHTryStmtClass:
469     case Stmt::SEHExceptStmtClass:
470     case Stmt::SEHFinallyStmtClass:
471     {
472       SaveAndRestore<bool> OldSink(Builder->BuildSinks);
473       Builder->BuildSinks = true;
474       const ExplodedNode *node = MakeNode(Dst, S, Pred, GetState(Pred));
475       Engine.addAbortedBlock(node, Builder->getBlock());
476       break;
477     }
478 
479     // We don't handle default arguments either yet, but we can fake it
480     // for now by just skipping them.
481     case Stmt::CXXDefaultArgExprClass: {
482       Dst.Add(Pred);
483       break;
484     }
485 
486     case Stmt::ParenExprClass:
487       llvm_unreachable("ParenExprs already handled.");
488     case Stmt::GenericSelectionExprClass:
489       llvm_unreachable("GenericSelectionExprs already handled.");
490     // Cases that should never be evaluated simply because they shouldn't
491     // appear in the CFG.
492     case Stmt::BreakStmtClass:
493     case Stmt::CaseStmtClass:
494     case Stmt::CompoundStmtClass:
495     case Stmt::ContinueStmtClass:
496     case Stmt::DefaultStmtClass:
497     case Stmt::DoStmtClass:
498     case Stmt::ForStmtClass:
499     case Stmt::GotoStmtClass:
500     case Stmt::IfStmtClass:
501     case Stmt::IndirectGotoStmtClass:
502     case Stmt::LabelStmtClass:
503     case Stmt::NoStmtClass:
504     case Stmt::NullStmtClass:
505     case Stmt::SwitchStmtClass:
506     case Stmt::WhileStmtClass:
507       llvm_unreachable("Stmt should not be in analyzer evaluation loop");
508       break;
509 
510     case Stmt::GNUNullExprClass: {
511       MakeNode(Dst, S, Pred, GetState(Pred)->BindExpr(S, svalBuilder.makeNull()));
512       break;
513     }
514 
515     case Stmt::ObjCAtSynchronizedStmtClass:
516       VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
517       break;
518 
519     case Stmt::ObjCPropertyRefExprClass:
520       VisitObjCPropertyRefExpr(cast<ObjCPropertyRefExpr>(S), Pred, Dst);
521       break;
522 
523     // Cases not handled yet; but will handle some day.
524     case Stmt::DesignatedInitExprClass:
525     case Stmt::ExtVectorElementExprClass:
526     case Stmt::ImaginaryLiteralClass:
527     case Stmt::ImplicitValueInitExprClass:
528     case Stmt::ObjCAtCatchStmtClass:
529     case Stmt::ObjCAtFinallyStmtClass:
530     case Stmt::ObjCAtTryStmtClass:
531     case Stmt::ObjCEncodeExprClass:
532     case Stmt::ObjCIsaExprClass:
533     case Stmt::ObjCProtocolExprClass:
534     case Stmt::ObjCSelectorExprClass:
535     case Stmt::ObjCStringLiteralClass:
536     case Stmt::ParenListExprClass:
537     case Stmt::PredefinedExprClass:
538     case Stmt::ShuffleVectorExprClass:
539     case Stmt::VAArgExprClass:
540     case Stmt::CUDAKernelCallExprClass:
541     case Stmt::OpaqueValueExprClass:
542         // Fall through.
543 
544     // Cases we intentionally don't evaluate, since they don't need
545     // to be explicitly evaluated.
546     case Stmt::AddrLabelExprClass:
547     case Stmt::IntegerLiteralClass:
548     case Stmt::CharacterLiteralClass:
549     case Stmt::CXXBoolLiteralExprClass:
550     case Stmt::ExprWithCleanupsClass:
551     case Stmt::FloatingLiteralClass:
552     case Stmt::SizeOfPackExprClass:
553     case Stmt::CXXNullPtrLiteralExprClass:
554       Dst.Add(Pred); // No-op. Simply propagate the current state unchanged.
555       break;
556 
557     case Stmt::ArraySubscriptExprClass:
558       VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
559       break;
560 
561     case Stmt::AsmStmtClass:
562       VisitAsmStmt(cast<AsmStmt>(S), Pred, Dst);
563       break;
564 
565     case Stmt::BlockDeclRefExprClass: {
566       const BlockDeclRefExpr *BE = cast<BlockDeclRefExpr>(S);
567       VisitCommonDeclRefExpr(BE, BE->getDecl(), Pred, Dst);
568       break;
569     }
570 
571     case Stmt::BlockExprClass:
572       VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
573       break;
574 
575     case Stmt::BinaryOperatorClass: {
576       const BinaryOperator* B = cast<BinaryOperator>(S);
577       if (B->isLogicalOp()) {
578         VisitLogicalExpr(B, Pred, Dst);
579         break;
580       }
581       else if (B->getOpcode() == BO_Comma) {
582         const GRState* state = GetState(Pred);
583         MakeNode(Dst, B, Pred, state->BindExpr(B, state->getSVal(B->getRHS())));
584         break;
585       }
586 
587       if (AMgr.shouldEagerlyAssume() &&
588           (B->isRelationalOp() || B->isEqualityOp())) {
589         ExplodedNodeSet Tmp;
590         VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
591         evalEagerlyAssume(Dst, Tmp, cast<Expr>(S));
592       }
593       else
594         VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
595 
596       break;
597     }
598 
599     case Stmt::CallExprClass:
600     case Stmt::CXXOperatorCallExprClass:
601     case Stmt::CXXMemberCallExprClass: {
602       VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
603       break;
604     }
605 
606     case Stmt::CXXConstructExprClass: {
607       const CXXConstructExpr *C = cast<CXXConstructExpr>(S);
608       // For block-level CXXConstructExpr, we don't have a destination region.
609       // Let VisitCXXConstructExpr() create one.
610       VisitCXXConstructExpr(C, 0, Pred, Dst);
611       break;
612     }
613 
614     case Stmt::CXXNewExprClass: {
615       const CXXNewExpr *NE = cast<CXXNewExpr>(S);
616       VisitCXXNewExpr(NE, Pred, Dst);
617       break;
618     }
619 
620     case Stmt::CXXDeleteExprClass: {
621       const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
622       VisitCXXDeleteExpr(CDE, Pred, Dst);
623       break;
624     }
625       // FIXME: ChooseExpr is really a constant.  We need to fix
626       //        the CFG do not model them as explicit control-flow.
627 
628     case Stmt::ChooseExprClass: { // __builtin_choose_expr
629       const ChooseExpr* C = cast<ChooseExpr>(S);
630       VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
631       break;
632     }
633 
634     case Stmt::CompoundAssignOperatorClass:
635       VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
636       break;
637 
638     case Stmt::CompoundLiteralExprClass:
639       VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
640       break;
641 
642     case Stmt::BinaryConditionalOperatorClass:
643     case Stmt::ConditionalOperatorClass: { // '?' operator
644       const AbstractConditionalOperator *C
645         = cast<AbstractConditionalOperator>(S);
646       VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
647       break;
648     }
649 
650     case Stmt::CXXThisExprClass:
651       VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
652       break;
653 
654     case Stmt::DeclRefExprClass: {
655       const DeclRefExpr *DE = cast<DeclRefExpr>(S);
656       VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
657       break;
658     }
659 
660     case Stmt::DeclStmtClass:
661       VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
662       break;
663 
664     case Stmt::ImplicitCastExprClass:
665     case Stmt::CStyleCastExprClass:
666     case Stmt::CXXStaticCastExprClass:
667     case Stmt::CXXDynamicCastExprClass:
668     case Stmt::CXXReinterpretCastExprClass:
669     case Stmt::CXXConstCastExprClass:
670     case Stmt::CXXFunctionalCastExprClass: {
671       const CastExpr* C = cast<CastExpr>(S);
672       VisitCast(C, C->getSubExpr(), Pred, Dst);
673       break;
674     }
675 
676     case Stmt::InitListExprClass:
677       VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
678       break;
679 
680     case Stmt::MemberExprClass:
681       VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
682       break;
683     case Stmt::ObjCIvarRefExprClass:
684       VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
685       break;
686 
687     case Stmt::ObjCForCollectionStmtClass:
688       VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
689       break;
690 
691     case Stmt::ObjCMessageExprClass:
692       VisitObjCMessageExpr(cast<ObjCMessageExpr>(S), Pred, Dst);
693       break;
694 
695     case Stmt::ObjCAtThrowStmtClass: {
696       // FIXME: This is not complete.  We basically treat @throw as
697       // an abort.
698       SaveAndRestore<bool> OldSink(Builder->BuildSinks);
699       Builder->BuildSinks = true;
700       MakeNode(Dst, S, Pred, GetState(Pred));
701       break;
702     }
703 
704     case Stmt::ReturnStmtClass:
705       VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
706       break;
707 
708     case Stmt::OffsetOfExprClass:
709       VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
710       break;
711 
712     case Stmt::UnaryExprOrTypeTraitExprClass:
713       VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
714                                     Pred, Dst);
715       break;
716 
717     case Stmt::StmtExprClass: {
718       const StmtExpr* SE = cast<StmtExpr>(S);
719 
720       if (SE->getSubStmt()->body_empty()) {
721         // Empty statement expression.
722         assert(SE->getType() == getContext().VoidTy
723                && "Empty statement expression must have void type.");
724         Dst.Add(Pred);
725         break;
726       }
727 
728       if (Expr* LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
729         const GRState* state = GetState(Pred);
730         MakeNode(Dst, SE, Pred, state->BindExpr(SE, state->getSVal(LastExpr)));
731       }
732       else
733         Dst.Add(Pred);
734 
735       break;
736     }
737 
738     case Stmt::StringLiteralClass: {
739       const GRState* state = GetState(Pred);
740       SVal V = state->getLValue(cast<StringLiteral>(S));
741       MakeNode(Dst, S, Pred, state->BindExpr(S, V));
742       return;
743     }
744 
745     case Stmt::UnaryOperatorClass: {
746       const UnaryOperator *U = cast<UnaryOperator>(S);
747       if (AMgr.shouldEagerlyAssume()&&(U->getOpcode() == UO_LNot)) {
748         ExplodedNodeSet Tmp;
749         VisitUnaryOperator(U, Pred, Tmp);
750         evalEagerlyAssume(Dst, Tmp, U);
751       }
752       else
753         VisitUnaryOperator(U, Pred, Dst);
754       break;
755     }
756   }
757 }
758 
759 //===----------------------------------------------------------------------===//
760 // Block entrance.  (Update counters).
761 //===----------------------------------------------------------------------===//
762 
763 void ExprEngine::processCFGBlockEntrance(ExplodedNodeSet &dstNodes,
764                                GenericNodeBuilder<BlockEntrance> &nodeBuilder){
765 
766   // FIXME: Refactor this into a checker.
767   const CFGBlock *block = nodeBuilder.getProgramPoint().getBlock();
768   ExplodedNode *pred = nodeBuilder.getPredecessor();
769 
770   if (nodeBuilder.getBlockCounter().getNumVisited(
771                        pred->getLocationContext()->getCurrentStackFrame(),
772                        block->getBlockID()) >= AMgr.getMaxVisit()) {
773 
774     static int tag = 0;
775     nodeBuilder.generateNode(pred->getState(), pred, &tag, true);
776   }
777 }
778 
779 //===----------------------------------------------------------------------===//
780 // Generic node creation.
781 //===----------------------------------------------------------------------===//
782 
783 ExplodedNode* ExprEngine::MakeNode(ExplodedNodeSet& Dst, const Stmt* S,
784                                      ExplodedNode* Pred, const GRState* St,
785                                      ProgramPoint::Kind K, const void *tag) {
786   assert (Builder && "StmtNodeBuilder not present.");
787   SaveAndRestore<const void*> OldTag(Builder->Tag);
788   Builder->Tag = tag;
789   return Builder->MakeNode(Dst, S, Pred, St, K);
790 }
791 
792 //===----------------------------------------------------------------------===//
793 // Branch processing.
794 //===----------------------------------------------------------------------===//
795 
796 const GRState* ExprEngine::MarkBranch(const GRState* state,
797                                         const Stmt* Terminator,
798                                         bool branchTaken) {
799 
800   switch (Terminator->getStmtClass()) {
801     default:
802       return state;
803 
804     case Stmt::BinaryOperatorClass: { // '&&' and '||'
805 
806       const BinaryOperator* B = cast<BinaryOperator>(Terminator);
807       BinaryOperator::Opcode Op = B->getOpcode();
808 
809       assert (Op == BO_LAnd || Op == BO_LOr);
810 
811       // For &&, if we take the true branch, then the value of the whole
812       // expression is that of the RHS expression.
813       //
814       // For ||, if we take the false branch, then the value of the whole
815       // expression is that of the RHS expression.
816 
817       const Expr* Ex = (Op == BO_LAnd && branchTaken) ||
818                        (Op == BO_LOr && !branchTaken)
819                        ? B->getRHS() : B->getLHS();
820 
821       return state->BindExpr(B, UndefinedVal(Ex));
822     }
823 
824     case Stmt::BinaryConditionalOperatorClass:
825     case Stmt::ConditionalOperatorClass: { // ?:
826       const AbstractConditionalOperator* C
827         = cast<AbstractConditionalOperator>(Terminator);
828 
829       // For ?, if branchTaken == true then the value is either the LHS or
830       // the condition itself. (GNU extension).
831 
832       const Expr* Ex;
833 
834       if (branchTaken)
835         Ex = C->getTrueExpr();
836       else
837         Ex = C->getFalseExpr();
838 
839       return state->BindExpr(C, UndefinedVal(Ex));
840     }
841 
842     case Stmt::ChooseExprClass: { // ?:
843 
844       const ChooseExpr* C = cast<ChooseExpr>(Terminator);
845 
846       const Expr* Ex = branchTaken ? C->getLHS() : C->getRHS();
847       return state->BindExpr(C, UndefinedVal(Ex));
848     }
849   }
850 }
851 
852 /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
853 /// to try to recover some path-sensitivity for casts of symbolic
854 /// integers that promote their values (which are currently not tracked well).
855 /// This function returns the SVal bound to Condition->IgnoreCasts if all the
856 //  cast(s) did was sign-extend the original value.
857 static SVal RecoverCastedSymbol(GRStateManager& StateMgr, const GRState* state,
858                                 const Stmt* Condition, ASTContext& Ctx) {
859 
860   const Expr *Ex = dyn_cast<Expr>(Condition);
861   if (!Ex)
862     return UnknownVal();
863 
864   uint64_t bits = 0;
865   bool bitsInit = false;
866 
867   while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
868     QualType T = CE->getType();
869 
870     if (!T->isIntegerType())
871       return UnknownVal();
872 
873     uint64_t newBits = Ctx.getTypeSize(T);
874     if (!bitsInit || newBits < bits) {
875       bitsInit = true;
876       bits = newBits;
877     }
878 
879     Ex = CE->getSubExpr();
880   }
881 
882   // We reached a non-cast.  Is it a symbolic value?
883   QualType T = Ex->getType();
884 
885   if (!bitsInit || !T->isIntegerType() || Ctx.getTypeSize(T) > bits)
886     return UnknownVal();
887 
888   return state->getSVal(Ex);
889 }
890 
891 void ExprEngine::processBranch(const Stmt* Condition, const Stmt* Term,
892                                  BranchNodeBuilder& builder) {
893 
894   // Check for NULL conditions; e.g. "for(;;)"
895   if (!Condition) {
896     builder.markInfeasible(false);
897     return;
898   }
899 
900   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
901                                 Condition->getLocStart(),
902                                 "Error evaluating branch");
903 
904   getCheckerManager().runCheckersForBranchCondition(Condition, builder, *this);
905 
906   // If the branch condition is undefined, return;
907   if (!builder.isFeasible(true) && !builder.isFeasible(false))
908     return;
909 
910   const GRState* PrevState = builder.getState();
911   SVal X = PrevState->getSVal(Condition);
912 
913   if (X.isUnknownOrUndef()) {
914     // Give it a chance to recover from unknown.
915     if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
916       if (Ex->getType()->isIntegerType()) {
917         // Try to recover some path-sensitivity.  Right now casts of symbolic
918         // integers that promote their values are currently not tracked well.
919         // If 'Condition' is such an expression, try and recover the
920         // underlying value and use that instead.
921         SVal recovered = RecoverCastedSymbol(getStateManager(),
922                                              builder.getState(), Condition,
923                                              getContext());
924 
925         if (!recovered.isUnknown()) {
926           X = recovered;
927         }
928       }
929     }
930     // If the condition is still unknown, give up.
931     if (X.isUnknownOrUndef()) {
932       builder.generateNode(MarkBranch(PrevState, Term, true), true);
933       builder.generateNode(MarkBranch(PrevState, Term, false), false);
934       return;
935     }
936   }
937 
938   DefinedSVal V = cast<DefinedSVal>(X);
939 
940   // Process the true branch.
941   if (builder.isFeasible(true)) {
942     if (const GRState *state = PrevState->assume(V, true))
943       builder.generateNode(MarkBranch(state, Term, true), true);
944     else
945       builder.markInfeasible(true);
946   }
947 
948   // Process the false branch.
949   if (builder.isFeasible(false)) {
950     if (const GRState *state = PrevState->assume(V, false))
951       builder.generateNode(MarkBranch(state, Term, false), false);
952     else
953       builder.markInfeasible(false);
954   }
955 }
956 
957 /// processIndirectGoto - Called by CoreEngine.  Used to generate successor
958 ///  nodes by processing the 'effects' of a computed goto jump.
959 void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
960 
961   const GRState *state = builder.getState();
962   SVal V = state->getSVal(builder.getTarget());
963 
964   // Three possibilities:
965   //
966   //   (1) We know the computed label.
967   //   (2) The label is NULL (or some other constant), or Undefined.
968   //   (3) We have no clue about the label.  Dispatch to all targets.
969   //
970 
971   typedef IndirectGotoNodeBuilder::iterator iterator;
972 
973   if (isa<loc::GotoLabel>(V)) {
974     const LabelDecl *L = cast<loc::GotoLabel>(V).getLabel();
975 
976     for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
977       if (I.getLabel() == L) {
978         builder.generateNode(I, state);
979         return;
980       }
981     }
982 
983     assert(false && "No block with label.");
984     return;
985   }
986 
987   if (isa<loc::ConcreteInt>(V) || isa<UndefinedVal>(V)) {
988     // Dispatch to the first target and mark it as a sink.
989     //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
990     // FIXME: add checker visit.
991     //    UndefBranches.insert(N);
992     return;
993   }
994 
995   // This is really a catch-all.  We don't support symbolics yet.
996   // FIXME: Implement dispatch for symbolic pointers.
997 
998   for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
999     builder.generateNode(I, state);
1000 }
1001 
1002 
1003 void ExprEngine::VisitGuardedExpr(const Expr* Ex, const Expr* L,
1004                                     const Expr* R,
1005                                     ExplodedNode* Pred, ExplodedNodeSet& Dst) {
1006 
1007   assert(Ex == currentStmt &&
1008          Pred->getLocationContext()->getCFG()->isBlkExpr(Ex));
1009 
1010   const GRState* state = GetState(Pred);
1011   SVal X = state->getSVal(Ex);
1012 
1013   assert (X.isUndef());
1014 
1015   const Expr *SE = (Expr*) cast<UndefinedVal>(X).getData();
1016   assert(SE);
1017   X = state->getSVal(SE);
1018 
1019   // Make sure that we invalidate the previous binding.
1020   MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, X, true));
1021 }
1022 
1023 /// ProcessEndPath - Called by CoreEngine.  Used to generate end-of-path
1024 ///  nodes when the control reaches the end of a function.
1025 void ExprEngine::processEndOfFunction(EndOfFunctionNodeBuilder& builder) {
1026   getTF().evalEndPath(*this, builder);
1027   StateMgr.EndPath(builder.getState());
1028   getCheckerManager().runCheckersForEndPath(builder, *this);
1029 }
1030 
1031 /// ProcessSwitch - Called by CoreEngine.  Used to generate successor
1032 ///  nodes by processing the 'effects' of a switch statement.
1033 void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
1034   typedef SwitchNodeBuilder::iterator iterator;
1035   const GRState* state = builder.getState();
1036   const Expr* CondE = builder.getCondition();
1037   SVal  CondV_untested = state->getSVal(CondE);
1038 
1039   if (CondV_untested.isUndef()) {
1040     //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
1041     // FIXME: add checker
1042     //UndefBranches.insert(N);
1043 
1044     return;
1045   }
1046   DefinedOrUnknownSVal CondV = cast<DefinedOrUnknownSVal>(CondV_untested);
1047 
1048   const GRState *DefaultSt = state;
1049 
1050   iterator I = builder.begin(), EI = builder.end();
1051   bool defaultIsFeasible = I == EI;
1052 
1053   for ( ; I != EI; ++I) {
1054     // Successor may be pruned out during CFG construction.
1055     if (!I.getBlock())
1056       continue;
1057 
1058     const CaseStmt* Case = I.getCase();
1059 
1060     // Evaluate the LHS of the case value.
1061     Expr::EvalResult V1;
1062     bool b = Case->getLHS()->Evaluate(V1, getContext());
1063 
1064     // Sanity checks.  These go away in Release builds.
1065     assert(b && V1.Val.isInt() && !V1.HasSideEffects
1066              && "Case condition must evaluate to an integer constant.");
1067     (void)b; // silence unused variable warning
1068     assert(V1.Val.getInt().getBitWidth() ==
1069            getContext().getTypeSize(CondE->getType()));
1070 
1071     // Get the RHS of the case, if it exists.
1072     Expr::EvalResult V2;
1073 
1074     if (const Expr* E = Case->getRHS()) {
1075       b = E->Evaluate(V2, getContext());
1076       assert(b && V2.Val.isInt() && !V2.HasSideEffects
1077              && "Case condition must evaluate to an integer constant.");
1078       (void)b; // silence unused variable warning
1079     }
1080     else
1081       V2 = V1;
1082 
1083     // FIXME: Eventually we should replace the logic below with a range
1084     //  comparison, rather than concretize the values within the range.
1085     //  This should be easy once we have "ranges" for NonLVals.
1086 
1087     do {
1088       nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1.Val.getInt()));
1089       DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state,
1090                                                CondV, CaseVal);
1091 
1092       // Now "assume" that the case matches.
1093       if (const GRState* stateNew = state->assume(Res, true)) {
1094         builder.generateCaseStmtNode(I, stateNew);
1095 
1096         // If CondV evaluates to a constant, then we know that this
1097         // is the *only* case that we can take, so stop evaluating the
1098         // others.
1099         if (isa<nonloc::ConcreteInt>(CondV))
1100           return;
1101       }
1102 
1103       // Now "assume" that the case doesn't match.  Add this state
1104       // to the default state (if it is feasible).
1105       if (DefaultSt) {
1106         if (const GRState *stateNew = DefaultSt->assume(Res, false)) {
1107           defaultIsFeasible = true;
1108           DefaultSt = stateNew;
1109         }
1110         else {
1111           defaultIsFeasible = false;
1112           DefaultSt = NULL;
1113         }
1114       }
1115 
1116       // Concretize the next value in the range.
1117       if (V1.Val.getInt() == V2.Val.getInt())
1118         break;
1119 
1120       ++V1.Val.getInt();
1121       assert (V1.Val.getInt() <= V2.Val.getInt());
1122 
1123     } while (true);
1124   }
1125 
1126   if (!defaultIsFeasible)
1127     return;
1128 
1129   // If we have switch(enum value), the default branch is not
1130   // feasible if all of the enum constants not covered by 'case:' statements
1131   // are not feasible values for the switch condition.
1132   //
1133   // Note that this isn't as accurate as it could be.  Even if there isn't
1134   // a case for a particular enum value as long as that enum value isn't
1135   // feasible then it shouldn't be considered for making 'default:' reachable.
1136   const SwitchStmt *SS = builder.getSwitch();
1137   const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
1138   if (CondExpr->getType()->getAs<EnumType>()) {
1139     if (SS->isAllEnumCasesCovered())
1140       return;
1141   }
1142 
1143   builder.generateDefaultCaseNode(DefaultSt);
1144 }
1145 
1146 void ExprEngine::processCallEnter(CallEnterNodeBuilder &B) {
1147   const GRState *state = B.getState()->enterStackFrame(B.getCalleeContext());
1148   B.generateNode(state);
1149 }
1150 
1151 void ExprEngine::processCallExit(CallExitNodeBuilder &B) {
1152   const GRState *state = B.getState();
1153   const ExplodedNode *Pred = B.getPredecessor();
1154   const StackFrameContext *calleeCtx =
1155                             cast<StackFrameContext>(Pred->getLocationContext());
1156   const Stmt *CE = calleeCtx->getCallSite();
1157 
1158   // If the callee returns an expression, bind its value to CallExpr.
1159   const Stmt *ReturnedExpr = state->get<ReturnExpr>();
1160   if (ReturnedExpr) {
1161     SVal RetVal = state->getSVal(ReturnedExpr);
1162     state = state->BindExpr(CE, RetVal);
1163     // Clear the return expr GDM.
1164     state = state->remove<ReturnExpr>();
1165   }
1166 
1167   // Bind the constructed object value to CXXConstructExpr.
1168   if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(CE)) {
1169     const CXXThisRegion *ThisR =
1170       getCXXThisRegion(CCE->getConstructor()->getParent(), calleeCtx);
1171 
1172     SVal ThisV = state->getSVal(ThisR);
1173     // Always bind the region to the CXXConstructExpr.
1174     state = state->BindExpr(CCE, ThisV);
1175   }
1176 
1177   B.generateNode(state);
1178 }
1179 
1180 //===----------------------------------------------------------------------===//
1181 // Transfer functions: logical operations ('&&', '||').
1182 //===----------------------------------------------------------------------===//
1183 
1184 void ExprEngine::VisitLogicalExpr(const BinaryOperator* B, ExplodedNode* Pred,
1185                                     ExplodedNodeSet& Dst) {
1186 
1187   assert(B->getOpcode() == BO_LAnd ||
1188          B->getOpcode() == BO_LOr);
1189 
1190   assert(B==currentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(B));
1191 
1192   const GRState* state = GetState(Pred);
1193   SVal X = state->getSVal(B);
1194   assert(X.isUndef());
1195 
1196   const Expr *Ex = (const Expr*) cast<UndefinedVal>(X).getData();
1197   assert(Ex);
1198 
1199   if (Ex == B->getRHS()) {
1200     X = state->getSVal(Ex);
1201 
1202     // Handle undefined values.
1203     if (X.isUndef()) {
1204       MakeNode(Dst, B, Pred, state->BindExpr(B, X));
1205       return;
1206     }
1207 
1208     DefinedOrUnknownSVal XD = cast<DefinedOrUnknownSVal>(X);
1209 
1210     // We took the RHS.  Because the value of the '&&' or '||' expression must
1211     // evaluate to 0 or 1, we must assume the value of the RHS evaluates to 0
1212     // or 1.  Alternatively, we could take a lazy approach, and calculate this
1213     // value later when necessary.  We don't have the machinery in place for
1214     // this right now, and since most logical expressions are used for branches,
1215     // the payoff is not likely to be large.  Instead, we do eager evaluation.
1216     if (const GRState *newState = state->assume(XD, true))
1217       MakeNode(Dst, B, Pred,
1218                newState->BindExpr(B, svalBuilder.makeIntVal(1U, B->getType())));
1219 
1220     if (const GRState *newState = state->assume(XD, false))
1221       MakeNode(Dst, B, Pred,
1222                newState->BindExpr(B, svalBuilder.makeIntVal(0U, B->getType())));
1223   }
1224   else {
1225     // We took the LHS expression.  Depending on whether we are '&&' or
1226     // '||' we know what the value of the expression is via properties of
1227     // the short-circuiting.
1228     X = svalBuilder.makeIntVal(B->getOpcode() == BO_LAnd ? 0U : 1U,
1229                           B->getType());
1230     MakeNode(Dst, B, Pred, state->BindExpr(B, X));
1231   }
1232 }
1233 
1234 //===----------------------------------------------------------------------===//
1235 // Transfer functions: Loads and stores.
1236 //===----------------------------------------------------------------------===//
1237 
1238 void ExprEngine::VisitBlockExpr(const BlockExpr *BE, ExplodedNode *Pred,
1239                                   ExplodedNodeSet &Dst) {
1240 
1241   ExplodedNodeSet Tmp;
1242 
1243   CanQualType T = getContext().getCanonicalType(BE->getType());
1244   SVal V = svalBuilder.getBlockPointer(BE->getBlockDecl(), T,
1245                                   Pred->getLocationContext());
1246 
1247   MakeNode(Tmp, BE, Pred, GetState(Pred)->BindExpr(BE, V),
1248            ProgramPoint::PostLValueKind);
1249 
1250   // Post-visit the BlockExpr.
1251   getCheckerManager().runCheckersForPostStmt(Dst, Tmp, BE, *this);
1252 }
1253 
1254 void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
1255                                         ExplodedNode *Pred,
1256                                         ExplodedNodeSet &Dst) {
1257   const GRState *state = GetState(Pred);
1258 
1259   if (const VarDecl* VD = dyn_cast<VarDecl>(D)) {
1260     assert(Ex->isLValue());
1261     SVal V = state->getLValue(VD, Pred->getLocationContext());
1262 
1263     // For references, the 'lvalue' is the pointer address stored in the
1264     // reference region.
1265     if (VD->getType()->isReferenceType()) {
1266       if (const MemRegion *R = V.getAsRegion())
1267         V = state->getSVal(R);
1268       else
1269         V = UnknownVal();
1270     }
1271 
1272     MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V),
1273              ProgramPoint::PostLValueKind);
1274     return;
1275   }
1276   if (const EnumConstantDecl* ED = dyn_cast<EnumConstantDecl>(D)) {
1277     assert(!Ex->isLValue());
1278     SVal V = svalBuilder.makeIntVal(ED->getInitVal());
1279     MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V));
1280     return;
1281   }
1282   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) {
1283     SVal V = svalBuilder.getFunctionPointer(FD);
1284     MakeNode(Dst, Ex, Pred, state->BindExpr(Ex, V),
1285              ProgramPoint::PostLValueKind);
1286     return;
1287   }
1288   assert (false &&
1289           "ValueDecl support for this ValueDecl not implemented.");
1290 }
1291 
1292 /// VisitArraySubscriptExpr - Transfer function for array accesses
1293 void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr* A,
1294                                              ExplodedNode* Pred,
1295                                              ExplodedNodeSet& Dst){
1296 
1297   const Expr* Base = A->getBase()->IgnoreParens();
1298   const Expr* Idx  = A->getIdx()->IgnoreParens();
1299 
1300   // Evaluate the base.
1301   ExplodedNodeSet Tmp;
1302   Visit(Base, Pred, Tmp);
1303 
1304   for (ExplodedNodeSet::iterator I1=Tmp.begin(), E1=Tmp.end(); I1!=E1; ++I1) {
1305     ExplodedNodeSet Tmp2;
1306     Visit(Idx, *I1, Tmp2);     // Evaluate the index.
1307     ExplodedNodeSet Tmp3;
1308     getCheckerManager().runCheckersForPreStmt(Tmp3, Tmp2, A, *this);
1309 
1310     for (ExplodedNodeSet::iterator I2=Tmp3.begin(),E2=Tmp3.end();I2!=E2; ++I2) {
1311       const GRState* state = GetState(*I2);
1312       SVal V = state->getLValue(A->getType(), state->getSVal(Idx),
1313                                 state->getSVal(Base));
1314       assert(A->isLValue());
1315       MakeNode(Dst, A, *I2, state->BindExpr(A, V), ProgramPoint::PostLValueKind);
1316     }
1317   }
1318 }
1319 
1320 /// VisitMemberExpr - Transfer function for member expressions.
1321 void ExprEngine::VisitMemberExpr(const MemberExpr* M, ExplodedNode* Pred,
1322                                  ExplodedNodeSet& Dst) {
1323 
1324   Expr *baseExpr = M->getBase()->IgnoreParens();
1325   ExplodedNodeSet dstBase;
1326   Visit(baseExpr, Pred, dstBase);
1327 
1328   FieldDecl *field = dyn_cast<FieldDecl>(M->getMemberDecl());
1329   if (!field) // FIXME: skipping member expressions for non-fields
1330     return;
1331 
1332   for (ExplodedNodeSet::iterator I = dstBase.begin(), E = dstBase.end();
1333     I != E; ++I) {
1334     const GRState* state = GetState(*I);
1335     SVal baseExprVal = state->getSVal(baseExpr);
1336     if (isa<nonloc::LazyCompoundVal>(baseExprVal) ||
1337         isa<nonloc::CompoundVal>(baseExprVal) ||
1338         // FIXME: This can originate by conjuring a symbol for an unknown
1339         // temporary struct object, see test/Analysis/fields.c:
1340         // (p = getit()).x
1341         isa<nonloc::SymbolVal>(baseExprVal)) {
1342       MakeNode(Dst, M, *I, state->BindExpr(M, UnknownVal()));
1343       continue;
1344     }
1345 
1346     // FIXME: Should we insert some assumption logic in here to determine
1347     // if "Base" is a valid piece of memory?  Before we put this assumption
1348     // later when using FieldOffset lvals (which we no longer have).
1349 
1350     // For all other cases, compute an lvalue.
1351     SVal L = state->getLValue(field, baseExprVal);
1352     if (M->isLValue())
1353       MakeNode(Dst, M, *I, state->BindExpr(M, L), ProgramPoint::PostLValueKind);
1354     else
1355       evalLoad(Dst, M, *I, state, L);
1356   }
1357 }
1358 
1359 /// evalBind - Handle the semantics of binding a value to a specific location.
1360 ///  This method is used by evalStore and (soon) VisitDeclStmt, and others.
1361 void ExprEngine::evalBind(ExplodedNodeSet& Dst, const Stmt* StoreE,
1362                             ExplodedNode* Pred, const GRState* state,
1363                             SVal location, SVal Val, bool atDeclInit) {
1364 
1365 
1366   // Do a previsit of the bind.
1367   ExplodedNodeSet CheckedSet, Src;
1368   Src.Add(Pred);
1369   getCheckerManager().runCheckersForBind(CheckedSet, Src, location, Val, StoreE,
1370                                          *this);
1371 
1372   for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
1373        I!=E; ++I) {
1374 
1375     if (Pred != *I)
1376       state = GetState(*I);
1377 
1378     const GRState* newState = 0;
1379 
1380     if (atDeclInit) {
1381       const VarRegion *VR =
1382         cast<VarRegion>(cast<loc::MemRegionVal>(location).getRegion());
1383 
1384       newState = state->bindDecl(VR, Val);
1385     }
1386     else {
1387       if (location.isUnknown()) {
1388         // We know that the new state will be the same as the old state since
1389         // the location of the binding is "unknown".  Consequently, there
1390         // is no reason to just create a new node.
1391         newState = state;
1392       }
1393       else {
1394         // We are binding to a value other than 'unknown'.  Perform the binding
1395         // using the StoreManager.
1396         newState = state->bindLoc(cast<Loc>(location), Val);
1397       }
1398     }
1399 
1400     // The next thing to do is check if the TransferFuncs object wants to
1401     // update the state based on the new binding.  If the GRTransferFunc object
1402     // doesn't do anything, just auto-propagate the current state.
1403 
1404     // NOTE: We use 'AssignE' for the location of the PostStore if 'AssignE'
1405     // is non-NULL.  Checkers typically care about
1406 
1407     StmtNodeBuilderRef BuilderRef(Dst, *Builder, *this, *I, newState, StoreE,
1408                                     true);
1409 
1410     getTF().evalBind(BuilderRef, location, Val);
1411   }
1412 }
1413 
1414 /// evalStore - Handle the semantics of a store via an assignment.
1415 ///  @param Dst The node set to store generated state nodes
1416 ///  @param AssignE The assignment expression if the store happens in an
1417 ///         assignment.
1418 ///  @param LocatioinE The location expression that is stored to.
1419 ///  @param state The current simulation state
1420 ///  @param location The location to store the value
1421 ///  @param Val The value to be stored
1422 void ExprEngine::evalStore(ExplodedNodeSet& Dst, const Expr *AssignE,
1423                              const Expr* LocationE,
1424                              ExplodedNode* Pred,
1425                              const GRState* state, SVal location, SVal Val,
1426                              const void *tag) {
1427 
1428   assert(Builder && "StmtNodeBuilder must be defined.");
1429 
1430   // Proceed with the store.  We use AssignE as the anchor for the PostStore
1431   // ProgramPoint if it is non-NULL, and LocationE otherwise.
1432   const Expr *StoreE = AssignE ? AssignE : LocationE;
1433 
1434   if (isa<loc::ObjCPropRef>(location)) {
1435     loc::ObjCPropRef prop = cast<loc::ObjCPropRef>(location);
1436     ExplodedNodeSet src = Pred;
1437     return VisitObjCMessage(ObjCPropertySetter(prop.getPropRefExpr(),
1438                                                StoreE, Val), src, Dst);
1439   }
1440 
1441   // Evaluate the location (checks for bad dereferences).
1442   ExplodedNodeSet Tmp;
1443   evalLocation(Tmp, LocationE, Pred, state, location, tag, false);
1444 
1445   if (Tmp.empty())
1446     return;
1447 
1448   if (location.isUndef())
1449     return;
1450 
1451   SaveAndRestore<ProgramPoint::Kind> OldSPointKind(Builder->PointKind,
1452                                                    ProgramPoint::PostStoreKind);
1453 
1454   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
1455     evalBind(Dst, StoreE, *NI, GetState(*NI), location, Val);
1456 }
1457 
1458 void ExprEngine::evalLoad(ExplodedNodeSet& Dst, const Expr *Ex,
1459                             ExplodedNode* Pred,
1460                             const GRState* state, SVal location,
1461                             const void *tag, QualType LoadTy) {
1462   assert(!isa<NonLoc>(location) && "location cannot be a NonLoc.");
1463 
1464   if (isa<loc::ObjCPropRef>(location)) {
1465     loc::ObjCPropRef prop = cast<loc::ObjCPropRef>(location);
1466     ExplodedNodeSet src = Pred;
1467     return VisitObjCMessage(ObjCPropertyGetter(prop.getPropRefExpr(), Ex),
1468                             src, Dst);
1469   }
1470 
1471   // Are we loading from a region?  This actually results in two loads; one
1472   // to fetch the address of the referenced value and one to fetch the
1473   // referenced value.
1474   if (const TypedRegion *TR =
1475         dyn_cast_or_null<TypedRegion>(location.getAsRegion())) {
1476 
1477     QualType ValTy = TR->getValueType();
1478     if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
1479       static int loadReferenceTag = 0;
1480       ExplodedNodeSet Tmp;
1481       evalLoadCommon(Tmp, Ex, Pred, state, location, &loadReferenceTag,
1482                      getContext().getPointerType(RT->getPointeeType()));
1483 
1484       // Perform the load from the referenced value.
1485       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
1486         state = GetState(*I);
1487         location = state->getSVal(Ex);
1488         evalLoadCommon(Dst, Ex, *I, state, location, tag, LoadTy);
1489       }
1490       return;
1491     }
1492   }
1493 
1494   evalLoadCommon(Dst, Ex, Pred, state, location, tag, LoadTy);
1495 }
1496 
1497 void ExprEngine::evalLoadCommon(ExplodedNodeSet& Dst, const Expr *Ex,
1498                                   ExplodedNode* Pred,
1499                                   const GRState* state, SVal location,
1500                                   const void *tag, QualType LoadTy) {
1501 
1502   // Evaluate the location (checks for bad dereferences).
1503   ExplodedNodeSet Tmp;
1504   evalLocation(Tmp, Ex, Pred, state, location, tag, true);
1505 
1506   if (Tmp.empty())
1507     return;
1508 
1509   if (location.isUndef())
1510     return;
1511 
1512   SaveAndRestore<ProgramPoint::Kind> OldSPointKind(Builder->PointKind);
1513 
1514   // Proceed with the load.
1515   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
1516     state = GetState(*NI);
1517 
1518     if (location.isUnknown()) {
1519       // This is important.  We must nuke the old binding.
1520       MakeNode(Dst, Ex, *NI, state->BindExpr(Ex, UnknownVal()),
1521                ProgramPoint::PostLoadKind, tag);
1522     }
1523     else {
1524       if (LoadTy.isNull())
1525         LoadTy = Ex->getType();
1526       SVal V = state->getSVal(cast<Loc>(location), LoadTy);
1527       MakeNode(Dst, Ex, *NI, state->bindExprAndLocation(Ex, location, V),
1528                ProgramPoint::PostLoadKind, tag);
1529     }
1530   }
1531 }
1532 
1533 void ExprEngine::evalLocation(ExplodedNodeSet &Dst, const Stmt *S,
1534                                 ExplodedNode* Pred,
1535                                 const GRState* state, SVal location,
1536                                 const void *tag, bool isLoad) {
1537   // Early checks for performance reason.
1538   if (location.isUnknown()) {
1539     Dst.Add(Pred);
1540     return;
1541   }
1542 
1543   ExplodedNodeSet Src;
1544   if (Builder->GetState(Pred) == state) {
1545     Src.Add(Pred);
1546   } else {
1547     // Associate this new state with an ExplodedNode.
1548     // FIXME: If I pass null tag, the graph is incorrect, e.g for
1549     //   int *p;
1550     //   p = 0;
1551     //   *p = 0xDEADBEEF;
1552     // "p = 0" is not noted as "Null pointer value stored to 'p'" but
1553     // instead "int *p" is noted as
1554     // "Variable 'p' initialized to a null pointer value"
1555     ExplodedNode *N = Builder->generateNode(S, state, Pred, this);
1556     Src.Add(N ? N : Pred);
1557   }
1558   getCheckerManager().runCheckersForLocation(Dst, Src, location, isLoad, S,
1559                                              *this);
1560 }
1561 
1562 bool ExprEngine::InlineCall(ExplodedNodeSet &Dst, const CallExpr *CE,
1563                               ExplodedNode *Pred) {
1564   return false;
1565 
1566   // Inlining isn't correct right now because we:
1567   // (a) don't generate CallExit nodes.
1568   // (b) we need a way to postpone doing post-visits of CallExprs until
1569   // the CallExit.  This means we need CallExits for the non-inline
1570   // cases as well.
1571 
1572 #if 0
1573   const GRState *state = GetState(Pred);
1574   const Expr *Callee = CE->getCallee();
1575   SVal L = state->getSVal(Callee);
1576 
1577   const FunctionDecl *FD = L.getAsFunctionDecl();
1578   if (!FD)
1579     return false;
1580 
1581   // Specially handle CXXMethods.
1582   const CXXMethodDecl *methodDecl = 0;
1583 
1584   switch (CE->getStmtClass()) {
1585     default: break;
1586     case Stmt::CXXOperatorCallExprClass: {
1587       const CXXOperatorCallExpr *opCall = cast<CXXOperatorCallExpr>(CE);
1588       methodDecl =
1589         llvm::dyn_cast_or_null<CXXMethodDecl>(opCall->getCalleeDecl());
1590       break;
1591     }
1592     case Stmt::CXXMemberCallExprClass: {
1593       const CXXMemberCallExpr *memberCall = cast<CXXMemberCallExpr>(CE);
1594       const MemberExpr *memberExpr =
1595         cast<MemberExpr>(memberCall->getCallee()->IgnoreParens());
1596       methodDecl = cast<CXXMethodDecl>(memberExpr->getMemberDecl());
1597       break;
1598     }
1599   }
1600 
1601 
1602 
1603 
1604   // Check if the function definition is in the same translation unit.
1605   if (FD->hasBody(FD)) {
1606     const StackFrameContext *stackFrame =
1607       AMgr.getStackFrame(AMgr.getAnalysisContext(FD),
1608                          Pred->getLocationContext(),
1609                          CE, Builder->getBlock(), Builder->getIndex());
1610     // Now we have the definition of the callee, create a CallEnter node.
1611     CallEnter Loc(CE, stackFrame, Pred->getLocationContext());
1612 
1613     ExplodedNode *N = Builder->generateNode(Loc, state, Pred);
1614     Dst.Add(N);
1615     return true;
1616   }
1617 
1618   // Check if we can find the function definition in other translation units.
1619   if (AMgr.hasIndexer()) {
1620     AnalysisContext *C = AMgr.getAnalysisContextInAnotherTU(FD);
1621     if (C == 0)
1622       return false;
1623     const StackFrameContext *stackFrame =
1624       AMgr.getStackFrame(C, Pred->getLocationContext(),
1625                          CE, Builder->getBlock(), Builder->getIndex());
1626     CallEnter Loc(CE, stackFrame, Pred->getLocationContext());
1627     ExplodedNode *N = Builder->generateNode(Loc, state, Pred);
1628     Dst.Add(N);
1629     return true;
1630   }
1631 
1632   // Generate the CallExit node.
1633 
1634   return false;
1635 #endif
1636 }
1637 
1638 void ExprEngine::VisitCallExpr(const CallExpr* CE, ExplodedNode* Pred,
1639                                ExplodedNodeSet& dst) {
1640 
1641   // Determine the type of function we're calling (if available).
1642   const FunctionProtoType *Proto = NULL;
1643   QualType FnType = CE->getCallee()->IgnoreParens()->getType();
1644   if (const PointerType *FnTypePtr = FnType->getAs<PointerType>())
1645     Proto = FnTypePtr->getPointeeType()->getAs<FunctionProtoType>();
1646 
1647   // Should the first argument be evaluated as an lvalue?
1648   bool firstArgumentAsLvalue = false;
1649   switch (CE->getStmtClass()) {
1650     case Stmt::CXXOperatorCallExprClass:
1651       firstArgumentAsLvalue = true;
1652       break;
1653     default:
1654       break;
1655   }
1656 
1657   // Evaluate the arguments.
1658   ExplodedNodeSet dstArgsEvaluated;
1659   evalArguments(CE->arg_begin(), CE->arg_end(), Proto, Pred, dstArgsEvaluated,
1660                 firstArgumentAsLvalue);
1661 
1662   // Evaluate the callee.
1663   ExplodedNodeSet dstCalleeEvaluated;
1664   evalCallee(CE, dstArgsEvaluated, dstCalleeEvaluated);
1665 
1666   // Perform the previsit of the CallExpr.
1667   ExplodedNodeSet dstPreVisit;
1668   getCheckerManager().runCheckersForPreStmt(dstPreVisit, dstCalleeEvaluated,
1669                                             CE, *this);
1670 
1671   // Now evaluate the call itself.
1672   class DefaultEval : public GraphExpander {
1673     ExprEngine &Eng;
1674     const CallExpr *CE;
1675   public:
1676 
1677     DefaultEval(ExprEngine &eng, const CallExpr *ce)
1678       : Eng(eng), CE(ce) {}
1679     virtual void expandGraph(ExplodedNodeSet &Dst, ExplodedNode *Pred) {
1680       // Should we inline the call?
1681       if (Eng.getAnalysisManager().shouldInlineCall() &&
1682           Eng.InlineCall(Dst, CE, Pred)) {
1683         return;
1684       }
1685 
1686       StmtNodeBuilder &Builder = Eng.getBuilder();
1687       assert(&Builder && "StmtNodeBuilder must be defined.");
1688 
1689       // Dispatch to the plug-in transfer function.
1690       unsigned oldSize = Dst.size();
1691       SaveOr OldHasGen(Builder.hasGeneratedNode);
1692 
1693       // Dispatch to transfer function logic to handle the call itself.
1694       const Expr* Callee = CE->getCallee()->IgnoreParens();
1695       const GRState* state = Eng.GetState(Pred);
1696       SVal L = state->getSVal(Callee);
1697       Eng.getTF().evalCall(Dst, Eng, Builder, CE, L, Pred);
1698 
1699       // Handle the case where no nodes where generated.  Auto-generate that
1700       // contains the updated state if we aren't generating sinks.
1701       if (!Builder.BuildSinks && Dst.size() == oldSize &&
1702           !Builder.hasGeneratedNode)
1703         Eng.MakeNode(Dst, CE, Pred, state);
1704     }
1705   };
1706 
1707   // Finally, evaluate the function call.  We try each of the checkers
1708   // to see if the can evaluate the function call.
1709   ExplodedNodeSet dstCallEvaluated;
1710   DefaultEval defEval(*this, CE);
1711   getCheckerManager().runCheckersForEvalCall(dstCallEvaluated,
1712                                              dstPreVisit,
1713                                              CE, *this, &defEval);
1714 
1715   // Finally, perform the post-condition check of the CallExpr and store
1716   // the created nodes in 'Dst'.
1717   getCheckerManager().runCheckersForPostStmt(dst, dstCallEvaluated, CE,
1718                                              *this);
1719 }
1720 
1721 //===----------------------------------------------------------------------===//
1722 // Transfer function: Objective-C dot-syntax to access a property.
1723 //===----------------------------------------------------------------------===//
1724 
1725 void ExprEngine::VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *Ex,
1726                                           ExplodedNode *Pred,
1727                                           ExplodedNodeSet &Dst) {
1728   ExplodedNodeSet dstBase;
1729 
1730   // Visit the receiver (if any).
1731   if (Ex->isObjectReceiver())
1732     Visit(Ex->getBase(), Pred, dstBase);
1733   else
1734     dstBase = Pred;
1735 
1736   ExplodedNodeSet dstPropRef;
1737 
1738   // Using the base, compute the lvalue of the instance variable.
1739   for (ExplodedNodeSet::iterator I = dstBase.begin(), E = dstBase.end();
1740        I!=E; ++I) {
1741     ExplodedNode *nodeBase = *I;
1742     const GRState *state = GetState(nodeBase);
1743     MakeNode(dstPropRef, Ex, *I, state->BindExpr(Ex, loc::ObjCPropRef(Ex)));
1744   }
1745 
1746   Dst.insert(dstPropRef);
1747 }
1748 
1749 //===----------------------------------------------------------------------===//
1750 // Transfer function: Objective-C ivar references.
1751 //===----------------------------------------------------------------------===//
1752 
1753 static std::pair<const void*,const void*> EagerlyAssumeTag
1754   = std::pair<const void*,const void*>(&EagerlyAssumeTag,static_cast<void*>(0));
1755 
1756 void ExprEngine::evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src,
1757                                      const Expr *Ex) {
1758   for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
1759     ExplodedNode *Pred = *I;
1760 
1761     // Test if the previous node was as the same expression.  This can happen
1762     // when the expression fails to evaluate to anything meaningful and
1763     // (as an optimization) we don't generate a node.
1764     ProgramPoint P = Pred->getLocation();
1765     if (!isa<PostStmt>(P) || cast<PostStmt>(P).getStmt() != Ex) {
1766       Dst.Add(Pred);
1767       continue;
1768     }
1769 
1770     const GRState* state = GetState(Pred);
1771     SVal V = state->getSVal(Ex);
1772     if (nonloc::SymExprVal *SEV = dyn_cast<nonloc::SymExprVal>(&V)) {
1773       // First assume that the condition is true.
1774       if (const GRState *stateTrue = state->assume(*SEV, true)) {
1775         stateTrue = stateTrue->BindExpr(Ex,
1776                                         svalBuilder.makeIntVal(1U, Ex->getType()));
1777         Dst.Add(Builder->generateNode(PostStmtCustom(Ex,
1778                                 &EagerlyAssumeTag, Pred->getLocationContext()),
1779                                       stateTrue, Pred));
1780       }
1781 
1782       // Next, assume that the condition is false.
1783       if (const GRState *stateFalse = state->assume(*SEV, false)) {
1784         stateFalse = stateFalse->BindExpr(Ex,
1785                                           svalBuilder.makeIntVal(0U, Ex->getType()));
1786         Dst.Add(Builder->generateNode(PostStmtCustom(Ex, &EagerlyAssumeTag,
1787                                                    Pred->getLocationContext()),
1788                                       stateFalse, Pred));
1789       }
1790     }
1791     else
1792       Dst.Add(Pred);
1793   }
1794 }
1795 
1796 //===----------------------------------------------------------------------===//
1797 // Transfer function: Objective-C @synchronized.
1798 //===----------------------------------------------------------------------===//
1799 
1800 void ExprEngine::VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
1801                                                ExplodedNode *Pred,
1802                                                ExplodedNodeSet &Dst) {
1803 
1804   // The mutex expression is a CFGElement, so we don't need to explicitly
1805   // visit it since it will already be processed.
1806 
1807   // Pre-visit the ObjCAtSynchronizedStmt.
1808   ExplodedNodeSet Tmp;
1809   Tmp.Add(Pred);
1810   getCheckerManager().runCheckersForPreStmt(Dst, Tmp, S, *this);
1811 }
1812 
1813 //===----------------------------------------------------------------------===//
1814 // Transfer function: Objective-C ivar references.
1815 //===----------------------------------------------------------------------===//
1816 
1817 void ExprEngine::VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr* Ex,
1818                                           ExplodedNode* Pred,
1819                                           ExplodedNodeSet& Dst) {
1820 
1821   // Visit the base expression, which is needed for computing the lvalue
1822   // of the ivar.
1823   ExplodedNodeSet dstBase;
1824   const Expr *baseExpr = Ex->getBase();
1825   Visit(baseExpr, Pred, dstBase);
1826 
1827   ExplodedNodeSet dstIvar;
1828 
1829   // Using the base, compute the lvalue of the instance variable.
1830   for (ExplodedNodeSet::iterator I = dstBase.begin(), E = dstBase.end();
1831        I!=E; ++I) {
1832     ExplodedNode *nodeBase = *I;
1833     const GRState *state = GetState(nodeBase);
1834     SVal baseVal = state->getSVal(baseExpr);
1835     SVal location = state->getLValue(Ex->getDecl(), baseVal);
1836     MakeNode(dstIvar, Ex, *I, state->BindExpr(Ex, location));
1837   }
1838 
1839   // Perform the post-condition check of the ObjCIvarRefExpr and store
1840   // the created nodes in 'Dst'.
1841   getCheckerManager().runCheckersForPostStmt(Dst, dstIvar, Ex, *this);
1842 }
1843 
1844 //===----------------------------------------------------------------------===//
1845 // Transfer function: Objective-C fast enumeration 'for' statements.
1846 //===----------------------------------------------------------------------===//
1847 
1848 void ExprEngine::VisitObjCForCollectionStmt(const ObjCForCollectionStmt* S,
1849                                      ExplodedNode* Pred, ExplodedNodeSet& Dst) {
1850 
1851   // ObjCForCollectionStmts are processed in two places.  This method
1852   // handles the case where an ObjCForCollectionStmt* occurs as one of the
1853   // statements within a basic block.  This transfer function does two things:
1854   //
1855   //  (1) binds the next container value to 'element'.  This creates a new
1856   //      node in the ExplodedGraph.
1857   //
1858   //  (2) binds the value 0/1 to the ObjCForCollectionStmt* itself, indicating
1859   //      whether or not the container has any more elements.  This value
1860   //      will be tested in ProcessBranch.  We need to explicitly bind
1861   //      this value because a container can contain nil elements.
1862   //
1863   // FIXME: Eventually this logic should actually do dispatches to
1864   //   'countByEnumeratingWithState:objects:count:' (NSFastEnumeration).
1865   //   This will require simulating a temporary NSFastEnumerationState, either
1866   //   through an SVal or through the use of MemRegions.  This value can
1867   //   be affixed to the ObjCForCollectionStmt* instead of 0/1; when the loop
1868   //   terminates we reclaim the temporary (it goes out of scope) and we
1869   //   we can test if the SVal is 0 or if the MemRegion is null (depending
1870   //   on what approach we take).
1871   //
1872   //  For now: simulate (1) by assigning either a symbol or nil if the
1873   //    container is empty.  Thus this transfer function will by default
1874   //    result in state splitting.
1875 
1876   const Stmt* elem = S->getElement();
1877   SVal ElementV;
1878 
1879   if (const DeclStmt* DS = dyn_cast<DeclStmt>(elem)) {
1880     const VarDecl* ElemD = cast<VarDecl>(DS->getSingleDecl());
1881     assert (ElemD->getInit() == 0);
1882     ElementV = GetState(Pred)->getLValue(ElemD, Pred->getLocationContext());
1883     VisitObjCForCollectionStmtAux(S, Pred, Dst, ElementV);
1884     return;
1885   }
1886 
1887   ExplodedNodeSet Tmp;
1888   Visit(cast<Expr>(elem), Pred, Tmp);
1889   for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I) {
1890     const GRState* state = GetState(*I);
1891     VisitObjCForCollectionStmtAux(S, *I, Dst, state->getSVal(elem));
1892   }
1893 }
1894 
1895 void ExprEngine::VisitObjCForCollectionStmtAux(const ObjCForCollectionStmt* S,
1896                                        ExplodedNode* Pred, ExplodedNodeSet& Dst,
1897                                                  SVal ElementV) {
1898 
1899   // Check if the location we are writing back to is a null pointer.
1900   const Stmt* elem = S->getElement();
1901   ExplodedNodeSet Tmp;
1902   evalLocation(Tmp, elem, Pred, GetState(Pred), ElementV, NULL, false);
1903 
1904   if (Tmp.empty())
1905     return;
1906 
1907   for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
1908     Pred = *NI;
1909     const GRState *state = GetState(Pred);
1910 
1911     // Handle the case where the container still has elements.
1912     SVal TrueV = svalBuilder.makeTruthVal(1);
1913     const GRState *hasElems = state->BindExpr(S, TrueV);
1914 
1915     // Handle the case where the container has no elements.
1916     SVal FalseV = svalBuilder.makeTruthVal(0);
1917     const GRState *noElems = state->BindExpr(S, FalseV);
1918 
1919     if (loc::MemRegionVal* MV = dyn_cast<loc::MemRegionVal>(&ElementV))
1920       if (const TypedRegion* R = dyn_cast<TypedRegion>(MV->getRegion())) {
1921         // FIXME: The proper thing to do is to really iterate over the
1922         //  container.  We will do this with dispatch logic to the store.
1923         //  For now, just 'conjure' up a symbolic value.
1924         QualType T = R->getValueType();
1925         assert(Loc::isLocType(T));
1926         unsigned Count = Builder->getCurrentBlockCount();
1927         SymbolRef Sym = SymMgr.getConjuredSymbol(elem, T, Count);
1928         SVal V = svalBuilder.makeLoc(Sym);
1929         hasElems = hasElems->bindLoc(ElementV, V);
1930 
1931         // Bind the location to 'nil' on the false branch.
1932         SVal nilV = svalBuilder.makeIntVal(0, T);
1933         noElems = noElems->bindLoc(ElementV, nilV);
1934       }
1935 
1936     // Create the new nodes.
1937     MakeNode(Dst, S, Pred, hasElems);
1938     MakeNode(Dst, S, Pred, noElems);
1939   }
1940 }
1941 
1942 //===----------------------------------------------------------------------===//
1943 // Transfer function: Objective-C message expressions.
1944 //===----------------------------------------------------------------------===//
1945 
1946 namespace {
1947 class ObjCMsgWLItem {
1948 public:
1949   ObjCMessageExpr::const_arg_iterator I;
1950   ExplodedNode *N;
1951 
1952   ObjCMsgWLItem(const ObjCMessageExpr::const_arg_iterator &i, ExplodedNode *n)
1953     : I(i), N(n) {}
1954 };
1955 } // end anonymous namespace
1956 
1957 void ExprEngine::VisitObjCMessageExpr(const ObjCMessageExpr* ME,
1958                                         ExplodedNode* Pred,
1959                                         ExplodedNodeSet& Dst){
1960 
1961   // Create a worklist to process both the arguments.
1962   llvm::SmallVector<ObjCMsgWLItem, 20> WL;
1963 
1964   // But first evaluate the receiver (if any).
1965   ObjCMessageExpr::const_arg_iterator AI = ME->arg_begin(), AE = ME->arg_end();
1966   if (const Expr *Receiver = ME->getInstanceReceiver()) {
1967     ExplodedNodeSet Tmp;
1968     Visit(Receiver, Pred, Tmp);
1969 
1970     if (Tmp.empty())
1971       return;
1972 
1973     for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I)
1974       WL.push_back(ObjCMsgWLItem(AI, *I));
1975   }
1976   else
1977     WL.push_back(ObjCMsgWLItem(AI, Pred));
1978 
1979   // Evaluate the arguments.
1980   ExplodedNodeSet ArgsEvaluated;
1981   while (!WL.empty()) {
1982     ObjCMsgWLItem Item = WL.back();
1983     WL.pop_back();
1984 
1985     if (Item.I == AE) {
1986       ArgsEvaluated.insert(Item.N);
1987       continue;
1988     }
1989 
1990     // Evaluate the subexpression.
1991     ExplodedNodeSet Tmp;
1992 
1993     // FIXME: [Objective-C++] handle arguments that are references
1994     Visit(*Item.I, Item.N, Tmp);
1995 
1996     // Enqueue evaluating the next argument on the worklist.
1997     ++(Item.I);
1998     for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
1999       WL.push_back(ObjCMsgWLItem(Item.I, *NI));
2000   }
2001 
2002   // Now that the arguments are processed, handle the ObjC message.
2003   VisitObjCMessage(ME, ArgsEvaluated, Dst);
2004 }
2005 
2006 void ExprEngine::VisitObjCMessage(const ObjCMessage &msg,
2007                                   ExplodedNodeSet &Src, ExplodedNodeSet& Dst) {
2008 
2009   // Handle the previsits checks.
2010   ExplodedNodeSet DstPrevisit;
2011   getCheckerManager().runCheckersForPreObjCMessage(DstPrevisit, Src, msg,*this);
2012 
2013   // Proceed with evaluate the message expression.
2014   ExplodedNodeSet dstEval;
2015 
2016   for (ExplodedNodeSet::iterator DI = DstPrevisit.begin(),
2017                                  DE = DstPrevisit.end(); DI != DE; ++DI) {
2018 
2019     ExplodedNode *Pred = *DI;
2020     bool RaisesException = false;
2021     unsigned oldSize = dstEval.size();
2022     SaveAndRestore<bool> OldSink(Builder->BuildSinks);
2023     SaveOr OldHasGen(Builder->hasGeneratedNode);
2024 
2025     if (const Expr *Receiver = msg.getInstanceReceiver()) {
2026       const GRState *state = GetState(Pred);
2027       SVal recVal = state->getSVal(Receiver);
2028       if (!recVal.isUndef()) {
2029         // Bifurcate the state into nil and non-nil ones.
2030         DefinedOrUnknownSVal receiverVal = cast<DefinedOrUnknownSVal>(recVal);
2031 
2032         const GRState *notNilState, *nilState;
2033         llvm::tie(notNilState, nilState) = state->assume(receiverVal);
2034 
2035         // There are three cases: can be nil or non-nil, must be nil, must be
2036         // non-nil. We ignore must be nil, and merge the rest two into non-nil.
2037         if (nilState && !notNilState) {
2038           dstEval.insert(Pred);
2039           continue;
2040         }
2041 
2042         // Check if the "raise" message was sent.
2043         assert(notNilState);
2044         if (msg.getSelector() == RaiseSel)
2045           RaisesException = true;
2046 
2047         // Check if we raise an exception.  For now treat these as sinks.
2048         // Eventually we will want to handle exceptions properly.
2049         if (RaisesException)
2050           Builder->BuildSinks = true;
2051 
2052         // Dispatch to plug-in transfer function.
2053         evalObjCMessage(dstEval, msg, Pred, notNilState);
2054       }
2055     }
2056     else if (const ObjCInterfaceDecl *Iface = msg.getReceiverInterface()) {
2057       IdentifierInfo* ClsName = Iface->getIdentifier();
2058       Selector S = msg.getSelector();
2059 
2060       // Check for special instance methods.
2061       if (!NSExceptionII) {
2062         ASTContext& Ctx = getContext();
2063         NSExceptionII = &Ctx.Idents.get("NSException");
2064       }
2065 
2066       if (ClsName == NSExceptionII) {
2067         enum { NUM_RAISE_SELECTORS = 2 };
2068 
2069         // Lazily create a cache of the selectors.
2070         if (!NSExceptionInstanceRaiseSelectors) {
2071           ASTContext& Ctx = getContext();
2072           NSExceptionInstanceRaiseSelectors =
2073             new Selector[NUM_RAISE_SELECTORS];
2074           llvm::SmallVector<IdentifierInfo*, NUM_RAISE_SELECTORS> II;
2075           unsigned idx = 0;
2076 
2077           // raise:format:
2078           II.push_back(&Ctx.Idents.get("raise"));
2079           II.push_back(&Ctx.Idents.get("format"));
2080           NSExceptionInstanceRaiseSelectors[idx++] =
2081             Ctx.Selectors.getSelector(II.size(), &II[0]);
2082 
2083           // raise:format::arguments:
2084           II.push_back(&Ctx.Idents.get("arguments"));
2085           NSExceptionInstanceRaiseSelectors[idx++] =
2086             Ctx.Selectors.getSelector(II.size(), &II[0]);
2087         }
2088 
2089         for (unsigned i = 0; i < NUM_RAISE_SELECTORS; ++i)
2090           if (S == NSExceptionInstanceRaiseSelectors[i]) {
2091             RaisesException = true;
2092             break;
2093           }
2094       }
2095 
2096       // Check if we raise an exception.  For now treat these as sinks.
2097       // Eventually we will want to handle exceptions properly.
2098       if (RaisesException)
2099         Builder->BuildSinks = true;
2100 
2101       // Dispatch to plug-in transfer function.
2102       evalObjCMessage(dstEval, msg, Pred, Builder->GetState(Pred));
2103     }
2104 
2105     // Handle the case where no nodes where generated.  Auto-generate that
2106     // contains the updated state if we aren't generating sinks.
2107     if (!Builder->BuildSinks && dstEval.size() == oldSize &&
2108         !Builder->hasGeneratedNode)
2109       MakeNode(dstEval, msg.getOriginExpr(), Pred, GetState(Pred));
2110   }
2111 
2112   // Finally, perform the post-condition check of the ObjCMessageExpr and store
2113   // the created nodes in 'Dst'.
2114   getCheckerManager().runCheckersForPostObjCMessage(Dst, dstEval, msg, *this);
2115 }
2116 
2117 //===----------------------------------------------------------------------===//
2118 // Transfer functions: Miscellaneous statements.
2119 //===----------------------------------------------------------------------===//
2120 
2121 void ExprEngine::VisitCast(const CastExpr *CastE, const Expr *Ex,
2122                            ExplodedNode *Pred, ExplodedNodeSet &Dst) {
2123 
2124   ExplodedNodeSet S1;
2125   Visit(Ex, Pred, S1);
2126   ExplodedNodeSet S2;
2127   getCheckerManager().runCheckersForPreStmt(S2, S1, CastE, *this);
2128 
2129   if (CastE->getCastKind() == CK_LValueToRValue ||
2130       CastE->getCastKind() == CK_GetObjCProperty) {
2131     for (ExplodedNodeSet::iterator I = S2.begin(), E = S2.end(); I!=E; ++I) {
2132       ExplodedNode *subExprNode = *I;
2133       const GRState *state = GetState(subExprNode);
2134       evalLoad(Dst, CastE, subExprNode, state, state->getSVal(Ex));
2135     }
2136     return;
2137   }
2138 
2139   // All other casts.
2140   QualType T = CastE->getType();
2141   QualType ExTy = Ex->getType();
2142 
2143   if (const ExplicitCastExpr *ExCast=dyn_cast_or_null<ExplicitCastExpr>(CastE))
2144     T = ExCast->getTypeAsWritten();
2145 
2146   for (ExplodedNodeSet::iterator I = S2.begin(), E = S2.end(); I != E; ++I) {
2147     Pred = *I;
2148 
2149     switch (CastE->getCastKind()) {
2150       case CK_ToVoid:
2151         Dst.Add(Pred);
2152         continue;
2153       case CK_LValueToRValue:
2154       case CK_NoOp:
2155       case CK_FunctionToPointerDecay: {
2156         // Copy the SVal of Ex to CastE.
2157         const GRState *state = GetState(Pred);
2158         SVal V = state->getSVal(Ex);
2159         state = state->BindExpr(CastE, V);
2160         MakeNode(Dst, CastE, Pred, state);
2161         continue;
2162       }
2163       case CK_GetObjCProperty:
2164       case CK_Dependent:
2165       case CK_ArrayToPointerDecay:
2166       case CK_BitCast:
2167       case CK_LValueBitCast:
2168       case CK_IntegralCast:
2169       case CK_NullToPointer:
2170       case CK_IntegralToPointer:
2171       case CK_PointerToIntegral:
2172       case CK_PointerToBoolean:
2173       case CK_IntegralToBoolean:
2174       case CK_IntegralToFloating:
2175       case CK_FloatingToIntegral:
2176       case CK_FloatingToBoolean:
2177       case CK_FloatingCast:
2178       case CK_FloatingRealToComplex:
2179       case CK_FloatingComplexToReal:
2180       case CK_FloatingComplexToBoolean:
2181       case CK_FloatingComplexCast:
2182       case CK_FloatingComplexToIntegralComplex:
2183       case CK_IntegralRealToComplex:
2184       case CK_IntegralComplexToReal:
2185       case CK_IntegralComplexToBoolean:
2186       case CK_IntegralComplexCast:
2187       case CK_IntegralComplexToFloatingComplex:
2188       case CK_AnyPointerToObjCPointerCast:
2189       case CK_AnyPointerToBlockPointerCast:
2190       case CK_ObjCObjectLValueCast: {
2191         // Delegate to SValBuilder to process.
2192         const GRState* state = GetState(Pred);
2193         SVal V = state->getSVal(Ex);
2194         V = svalBuilder.evalCast(V, T, ExTy);
2195         state = state->BindExpr(CastE, V);
2196         MakeNode(Dst, CastE, Pred, state);
2197         continue;
2198       }
2199       case CK_DerivedToBase:
2200       case CK_UncheckedDerivedToBase: {
2201         // For DerivedToBase cast, delegate to the store manager.
2202         const GRState *state = GetState(Pred);
2203         SVal val = state->getSVal(Ex);
2204         val = getStoreManager().evalDerivedToBase(val, T);
2205         state = state->BindExpr(CastE, val);
2206         MakeNode(Dst, CastE, Pred, state);
2207         continue;
2208       }
2209       // Various C++ casts that are not handled yet.
2210       case CK_Dynamic:
2211       case CK_ToUnion:
2212       case CK_BaseToDerived:
2213       case CK_NullToMemberPointer:
2214       case CK_BaseToDerivedMemberPointer:
2215       case CK_DerivedToBaseMemberPointer:
2216       case CK_UserDefinedConversion:
2217       case CK_ConstructorConversion:
2218       case CK_VectorSplat:
2219       case CK_MemberPointerToBoolean: {
2220         // Recover some path-sensitivty by conjuring a new value.
2221         QualType resultType = CastE->getType();
2222         if (CastE->isLValue())
2223           resultType = getContext().getPointerType(resultType);
2224 
2225         SVal result =
2226           svalBuilder.getConjuredSymbolVal(NULL, CastE, resultType,
2227                                            Builder->getCurrentBlockCount());
2228 
2229         const GRState *state = GetState(Pred)->BindExpr(CastE, result);
2230         MakeNode(Dst, CastE, Pred, state);
2231         continue;
2232       }
2233     }
2234   }
2235 }
2236 
2237 void ExprEngine::VisitCompoundLiteralExpr(const CompoundLiteralExpr* CL,
2238                                             ExplodedNode* Pred,
2239                                             ExplodedNodeSet& Dst) {
2240   const InitListExpr* ILE
2241     = cast<InitListExpr>(CL->getInitializer()->IgnoreParens());
2242   ExplodedNodeSet Tmp;
2243   Visit(ILE, Pred, Tmp);
2244 
2245   for (ExplodedNodeSet::iterator I = Tmp.begin(), EI = Tmp.end(); I!=EI; ++I) {
2246     const GRState* state = GetState(*I);
2247     SVal ILV = state->getSVal(ILE);
2248     const LocationContext *LC = (*I)->getLocationContext();
2249     state = state->bindCompoundLiteral(CL, LC, ILV);
2250 
2251     if (CL->isLValue()) {
2252       MakeNode(Dst, CL, *I, state->BindExpr(CL, state->getLValue(CL, LC)));
2253     }
2254     else
2255       MakeNode(Dst, CL, *I, state->BindExpr(CL, ILV));
2256   }
2257 }
2258 
2259 void ExprEngine::VisitDeclStmt(const DeclStmt *DS, ExplodedNode *Pred,
2260                                  ExplodedNodeSet& Dst) {
2261 
2262   // The CFG has one DeclStmt per Decl.
2263   const Decl* D = *DS->decl_begin();
2264 
2265   if (!D || !isa<VarDecl>(D))
2266     return;
2267 
2268   const VarDecl* VD = dyn_cast<VarDecl>(D);
2269   const Expr* InitEx = VD->getInit();
2270 
2271   // FIXME: static variables may have an initializer, but the second
2272   //  time a function is called those values may not be current.
2273   ExplodedNodeSet Tmp;
2274 
2275   if (InitEx) {
2276     if (VD->getType()->isReferenceType() && !InitEx->isLValue()) {
2277       // If the initializer is C++ record type, it should already has a
2278       // temp object.
2279       if (!InitEx->getType()->isRecordType())
2280         CreateCXXTemporaryObject(InitEx, Pred, Tmp);
2281       else
2282         Tmp.Add(Pred);
2283     } else
2284       Visit(InitEx, Pred, Tmp);
2285   } else
2286     Tmp.Add(Pred);
2287 
2288   ExplodedNodeSet Tmp2;
2289   getCheckerManager().runCheckersForPreStmt(Tmp2, Tmp, DS, *this);
2290 
2291   for (ExplodedNodeSet::iterator I=Tmp2.begin(), E=Tmp2.end(); I!=E; ++I) {
2292     ExplodedNode *N = *I;
2293     const GRState *state = GetState(N);
2294 
2295     // Decls without InitExpr are not initialized explicitly.
2296     const LocationContext *LC = N->getLocationContext();
2297 
2298     if (InitEx) {
2299       SVal InitVal = state->getSVal(InitEx);
2300 
2301       // We bound the temp obj region to the CXXConstructExpr. Now recover
2302       // the lazy compound value when the variable is not a reference.
2303       if (AMgr.getLangOptions().CPlusPlus && VD->getType()->isRecordType() &&
2304           !VD->getType()->isReferenceType() && isa<loc::MemRegionVal>(InitVal)){
2305         InitVal = state->getSVal(cast<loc::MemRegionVal>(InitVal).getRegion());
2306         assert(isa<nonloc::LazyCompoundVal>(InitVal));
2307       }
2308 
2309       // Recover some path-sensitivity if a scalar value evaluated to
2310       // UnknownVal.
2311       if ((InitVal.isUnknown() ||
2312           !getConstraintManager().canReasonAbout(InitVal)) &&
2313           !VD->getType()->isReferenceType()) {
2314         InitVal = svalBuilder.getConjuredSymbolVal(NULL, InitEx,
2315                                                Builder->getCurrentBlockCount());
2316       }
2317 
2318       evalBind(Dst, DS, *I, state,
2319                loc::MemRegionVal(state->getRegion(VD, LC)), InitVal, true);
2320     }
2321     else {
2322       state = state->bindDeclWithNoInit(state->getRegion(VD, LC));
2323       MakeNode(Dst, DS, *I, state);
2324     }
2325   }
2326 }
2327 
2328 namespace {
2329   // This class is used by VisitInitListExpr as an item in a worklist
2330   // for processing the values contained in an InitListExpr.
2331 class InitListWLItem {
2332 public:
2333   llvm::ImmutableList<SVal> Vals;
2334   ExplodedNode* N;
2335   InitListExpr::const_reverse_iterator Itr;
2336 
2337   InitListWLItem(ExplodedNode* n, llvm::ImmutableList<SVal> vals,
2338                  InitListExpr::const_reverse_iterator itr)
2339   : Vals(vals), N(n), Itr(itr) {}
2340 };
2341 }
2342 
2343 
2344 void ExprEngine::VisitInitListExpr(const InitListExpr* E, ExplodedNode* Pred,
2345                                      ExplodedNodeSet& Dst) {
2346 
2347   const GRState* state = GetState(Pred);
2348   QualType T = getContext().getCanonicalType(E->getType());
2349   unsigned NumInitElements = E->getNumInits();
2350 
2351   if (T->isArrayType() || T->isRecordType() || T->isVectorType()) {
2352     llvm::ImmutableList<SVal> StartVals = getBasicVals().getEmptySValList();
2353 
2354     // Handle base case where the initializer has no elements.
2355     // e.g: static int* myArray[] = {};
2356     if (NumInitElements == 0) {
2357       SVal V = svalBuilder.makeCompoundVal(T, StartVals);
2358       MakeNode(Dst, E, Pred, state->BindExpr(E, V));
2359       return;
2360     }
2361 
2362     // Create a worklist to process the initializers.
2363     llvm::SmallVector<InitListWLItem, 10> WorkList;
2364     WorkList.reserve(NumInitElements);
2365     WorkList.push_back(InitListWLItem(Pred, StartVals, E->rbegin()));
2366     InitListExpr::const_reverse_iterator ItrEnd = E->rend();
2367     assert(!(E->rbegin() == E->rend()));
2368 
2369     // Process the worklist until it is empty.
2370     while (!WorkList.empty()) {
2371       InitListWLItem X = WorkList.back();
2372       WorkList.pop_back();
2373 
2374       ExplodedNodeSet Tmp;
2375       Visit(*X.Itr, X.N, Tmp);
2376 
2377       InitListExpr::const_reverse_iterator NewItr = X.Itr + 1;
2378 
2379       for (ExplodedNodeSet::iterator NI=Tmp.begin(),NE=Tmp.end();NI!=NE;++NI) {
2380         // Get the last initializer value.
2381         state = GetState(*NI);
2382         SVal InitV = state->getSVal(cast<Expr>(*X.Itr));
2383 
2384         // Construct the new list of values by prepending the new value to
2385         // the already constructed list.
2386         llvm::ImmutableList<SVal> NewVals =
2387           getBasicVals().consVals(InitV, X.Vals);
2388 
2389         if (NewItr == ItrEnd) {
2390           // Now we have a list holding all init values. Make CompoundValData.
2391           SVal V = svalBuilder.makeCompoundVal(T, NewVals);
2392 
2393           // Make final state and node.
2394           MakeNode(Dst, E, *NI, state->BindExpr(E, V));
2395         }
2396         else {
2397           // Still some initializer values to go.  Push them onto the worklist.
2398           WorkList.push_back(InitListWLItem(*NI, NewVals, NewItr));
2399         }
2400       }
2401     }
2402 
2403     return;
2404   }
2405 
2406   if (Loc::isLocType(T) || T->isIntegerType()) {
2407     assert (E->getNumInits() == 1);
2408     ExplodedNodeSet Tmp;
2409     const Expr* Init = E->getInit(0);
2410     Visit(Init, Pred, Tmp);
2411     for (ExplodedNodeSet::iterator I=Tmp.begin(), EI=Tmp.end(); I != EI; ++I) {
2412       state = GetState(*I);
2413       MakeNode(Dst, E, *I, state->BindExpr(E, state->getSVal(Init)));
2414     }
2415     return;
2416   }
2417 
2418   assert(0 && "unprocessed InitListExpr type");
2419 }
2420 
2421 /// VisitUnaryExprOrTypeTraitExpr - Transfer function for sizeof(type).
2422 void ExprEngine::VisitUnaryExprOrTypeTraitExpr(
2423                                           const UnaryExprOrTypeTraitExpr* Ex,
2424                                           ExplodedNode* Pred,
2425                                           ExplodedNodeSet& Dst) {
2426   QualType T = Ex->getTypeOfArgument();
2427 
2428   if (Ex->getKind() == UETT_SizeOf) {
2429     if (!T->isIncompleteType() && !T->isConstantSizeType()) {
2430       assert(T->isVariableArrayType() && "Unknown non-constant-sized type.");
2431 
2432       // FIXME: Add support for VLA type arguments, not just VLA expressions.
2433       // When that happens, we should probably refactor VLASizeChecker's code.
2434       if (Ex->isArgumentType()) {
2435         Dst.Add(Pred);
2436         return;
2437       }
2438 
2439       // Get the size by getting the extent of the sub-expression.
2440       // First, visit the sub-expression to find its region.
2441       const Expr *Arg = Ex->getArgumentExpr();
2442       ExplodedNodeSet Tmp;
2443       Visit(Arg, Pred, Tmp);
2444 
2445       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
2446         const GRState* state = GetState(*I);
2447         const MemRegion *MR = state->getSVal(Arg).getAsRegion();
2448 
2449         // If the subexpression can't be resolved to a region, we don't know
2450         // anything about its size. Just leave the state as is and continue.
2451         if (!MR) {
2452           Dst.Add(*I);
2453           continue;
2454         }
2455 
2456         // The result is the extent of the VLA.
2457         SVal Extent = cast<SubRegion>(MR)->getExtent(svalBuilder);
2458         MakeNode(Dst, Ex, *I, state->BindExpr(Ex, Extent));
2459       }
2460 
2461       return;
2462     }
2463     else if (T->getAs<ObjCObjectType>()) {
2464       // Some code tries to take the sizeof an ObjCObjectType, relying that
2465       // the compiler has laid out its representation.  Just report Unknown
2466       // for these.
2467       Dst.Add(Pred);
2468       return;
2469     }
2470   }
2471 
2472   Expr::EvalResult Result;
2473   Ex->Evaluate(Result, getContext());
2474   CharUnits amt = CharUnits::fromQuantity(Result.Val.getInt().getZExtValue());
2475 
2476   MakeNode(Dst, Ex, Pred,
2477            GetState(Pred)->BindExpr(Ex,
2478               svalBuilder.makeIntVal(amt.getQuantity(), Ex->getType())));
2479 }
2480 
2481 void ExprEngine::VisitOffsetOfExpr(const OffsetOfExpr* OOE,
2482                                      ExplodedNode* Pred, ExplodedNodeSet& Dst) {
2483   Expr::EvalResult Res;
2484   if (OOE->Evaluate(Res, getContext()) && Res.Val.isInt()) {
2485     const APSInt &IV = Res.Val.getInt();
2486     assert(IV.getBitWidth() == getContext().getTypeSize(OOE->getType()));
2487     assert(OOE->getType()->isIntegerType());
2488     assert(IV.isSigned() == OOE->getType()->isSignedIntegerOrEnumerationType());
2489     SVal X = svalBuilder.makeIntVal(IV);
2490     MakeNode(Dst, OOE, Pred, GetState(Pred)->BindExpr(OOE, X));
2491     return;
2492   }
2493   // FIXME: Handle the case where __builtin_offsetof is not a constant.
2494   Dst.Add(Pred);
2495 }
2496 
2497 void ExprEngine::VisitUnaryOperator(const UnaryOperator* U,
2498                                       ExplodedNode* Pred,
2499                                       ExplodedNodeSet& Dst) {
2500 
2501   switch (U->getOpcode()) {
2502 
2503     default:
2504       break;
2505 
2506     case UO_Real: {
2507       const Expr* Ex = U->getSubExpr()->IgnoreParens();
2508       ExplodedNodeSet Tmp;
2509       Visit(Ex, Pred, Tmp);
2510 
2511       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
2512 
2513         // FIXME: We don't have complex SValues yet.
2514         if (Ex->getType()->isAnyComplexType()) {
2515           // Just report "Unknown."
2516           Dst.Add(*I);
2517           continue;
2518         }
2519 
2520         // For all other types, UO_Real is an identity operation.
2521         assert (U->getType() == Ex->getType());
2522         const GRState* state = GetState(*I);
2523         MakeNode(Dst, U, *I, state->BindExpr(U, state->getSVal(Ex)));
2524       }
2525 
2526       return;
2527     }
2528 
2529     case UO_Imag: {
2530 
2531       const Expr* Ex = U->getSubExpr()->IgnoreParens();
2532       ExplodedNodeSet Tmp;
2533       Visit(Ex, Pred, Tmp);
2534 
2535       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
2536         // FIXME: We don't have complex SValues yet.
2537         if (Ex->getType()->isAnyComplexType()) {
2538           // Just report "Unknown."
2539           Dst.Add(*I);
2540           continue;
2541         }
2542 
2543         // For all other types, UO_Imag returns 0.
2544         const GRState* state = GetState(*I);
2545         SVal X = svalBuilder.makeZeroVal(Ex->getType());
2546         MakeNode(Dst, U, *I, state->BindExpr(U, X));
2547       }
2548 
2549       return;
2550     }
2551 
2552     case UO_Plus:
2553       assert(!U->isLValue());
2554       // FALL-THROUGH.
2555     case UO_Deref:
2556     case UO_AddrOf:
2557     case UO_Extension: {
2558 
2559       // Unary "+" is a no-op, similar to a parentheses.  We still have places
2560       // where it may be a block-level expression, so we need to
2561       // generate an extra node that just propagates the value of the
2562       // subexpression.
2563 
2564       const Expr* Ex = U->getSubExpr()->IgnoreParens();
2565       ExplodedNodeSet Tmp;
2566       Visit(Ex, Pred, Tmp);
2567 
2568       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
2569         const GRState* state = GetState(*I);
2570         MakeNode(Dst, U, *I, state->BindExpr(U, state->getSVal(Ex)));
2571       }
2572 
2573       return;
2574     }
2575 
2576     case UO_LNot:
2577     case UO_Minus:
2578     case UO_Not: {
2579       assert (!U->isLValue());
2580       const Expr* Ex = U->getSubExpr()->IgnoreParens();
2581       ExplodedNodeSet Tmp;
2582       Visit(Ex, Pred, Tmp);
2583 
2584       for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
2585         const GRState* state = GetState(*I);
2586 
2587         // Get the value of the subexpression.
2588         SVal V = state->getSVal(Ex);
2589 
2590         if (V.isUnknownOrUndef()) {
2591           MakeNode(Dst, U, *I, state->BindExpr(U, V));
2592           continue;
2593         }
2594 
2595 //        QualType DstT = getContext().getCanonicalType(U->getType());
2596 //        QualType SrcT = getContext().getCanonicalType(Ex->getType());
2597 //
2598 //        if (DstT != SrcT) // Perform promotions.
2599 //          V = evalCast(V, DstT);
2600 //
2601 //        if (V.isUnknownOrUndef()) {
2602 //          MakeNode(Dst, U, *I, BindExpr(St, U, V));
2603 //          continue;
2604 //        }
2605 
2606         switch (U->getOpcode()) {
2607           default:
2608             assert(false && "Invalid Opcode.");
2609             break;
2610 
2611           case UO_Not:
2612             // FIXME: Do we need to handle promotions?
2613             state = state->BindExpr(U, evalComplement(cast<NonLoc>(V)));
2614             break;
2615 
2616           case UO_Minus:
2617             // FIXME: Do we need to handle promotions?
2618             state = state->BindExpr(U, evalMinus(cast<NonLoc>(V)));
2619             break;
2620 
2621           case UO_LNot:
2622 
2623             // C99 6.5.3.3: "The expression !E is equivalent to (0==E)."
2624             //
2625             //  Note: technically we do "E == 0", but this is the same in the
2626             //    transfer functions as "0 == E".
2627             SVal Result;
2628 
2629             if (isa<Loc>(V)) {
2630               Loc X = svalBuilder.makeNull();
2631               Result = evalBinOp(state, BO_EQ, cast<Loc>(V), X,
2632                                  U->getType());
2633             }
2634             else {
2635               nonloc::ConcreteInt X(getBasicVals().getValue(0, Ex->getType()));
2636               Result = evalBinOp(state, BO_EQ, cast<NonLoc>(V), X,
2637                                  U->getType());
2638             }
2639 
2640             state = state->BindExpr(U, Result);
2641 
2642             break;
2643         }
2644 
2645         MakeNode(Dst, U, *I, state);
2646       }
2647 
2648       return;
2649     }
2650   }
2651 
2652   // Handle ++ and -- (both pre- and post-increment).
2653   assert (U->isIncrementDecrementOp());
2654   ExplodedNodeSet Tmp;
2655   const Expr* Ex = U->getSubExpr()->IgnoreParens();
2656   Visit(Ex, Pred, Tmp);
2657 
2658   for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I!=E; ++I) {
2659 
2660     const GRState* state = GetState(*I);
2661     SVal loc = state->getSVal(Ex);
2662 
2663     // Perform a load.
2664     ExplodedNodeSet Tmp2;
2665     evalLoad(Tmp2, Ex, *I, state, loc);
2666 
2667     for (ExplodedNodeSet::iterator I2=Tmp2.begin(), E2=Tmp2.end();I2!=E2;++I2) {
2668 
2669       state = GetState(*I2);
2670       SVal V2_untested = state->getSVal(Ex);
2671 
2672       // Propagate unknown and undefined values.
2673       if (V2_untested.isUnknownOrUndef()) {
2674         MakeNode(Dst, U, *I2, state->BindExpr(U, V2_untested));
2675         continue;
2676       }
2677       DefinedSVal V2 = cast<DefinedSVal>(V2_untested);
2678 
2679       // Handle all other values.
2680       BinaryOperator::Opcode Op = U->isIncrementOp() ? BO_Add
2681                                                      : BO_Sub;
2682 
2683       // If the UnaryOperator has non-location type, use its type to create the
2684       // constant value. If the UnaryOperator has location type, create the
2685       // constant with int type and pointer width.
2686       SVal RHS;
2687 
2688       if (U->getType()->isAnyPointerType())
2689         RHS = svalBuilder.makeArrayIndex(1);
2690       else
2691         RHS = svalBuilder.makeIntVal(1, U->getType());
2692 
2693       SVal Result = evalBinOp(state, Op, V2, RHS, U->getType());
2694 
2695       // Conjure a new symbol if necessary to recover precision.
2696       if (Result.isUnknown() || !getConstraintManager().canReasonAbout(Result)){
2697         DefinedOrUnknownSVal SymVal =
2698           svalBuilder.getConjuredSymbolVal(NULL, Ex,
2699                                       Builder->getCurrentBlockCount());
2700         Result = SymVal;
2701 
2702         // If the value is a location, ++/-- should always preserve
2703         // non-nullness.  Check if the original value was non-null, and if so
2704         // propagate that constraint.
2705         if (Loc::isLocType(U->getType())) {
2706           DefinedOrUnknownSVal Constraint =
2707             svalBuilder.evalEQ(state, V2,svalBuilder.makeZeroVal(U->getType()));
2708 
2709           if (!state->assume(Constraint, true)) {
2710             // It isn't feasible for the original value to be null.
2711             // Propagate this constraint.
2712             Constraint = svalBuilder.evalEQ(state, SymVal,
2713                                        svalBuilder.makeZeroVal(U->getType()));
2714 
2715 
2716             state = state->assume(Constraint, false);
2717             assert(state);
2718           }
2719         }
2720       }
2721 
2722       // Since the lvalue-to-rvalue conversion is explicit in the AST,
2723       // we bind an l-value if the operator is prefix and an lvalue (in C++).
2724       if (U->isLValue())
2725         state = state->BindExpr(U, loc);
2726       else
2727         state = state->BindExpr(U, U->isPostfix() ? V2 : Result);
2728 
2729       // Perform the store.
2730       evalStore(Dst, NULL, U, *I2, state, loc, Result);
2731     }
2732   }
2733 }
2734 
2735 void ExprEngine::VisitAsmStmt(const AsmStmt* A, ExplodedNode* Pred,
2736                                 ExplodedNodeSet& Dst) {
2737   VisitAsmStmtHelperOutputs(A, A->begin_outputs(), A->end_outputs(), Pred, Dst);
2738 }
2739 
2740 void ExprEngine::VisitAsmStmtHelperOutputs(const AsmStmt* A,
2741                                              AsmStmt::const_outputs_iterator I,
2742                                              AsmStmt::const_outputs_iterator E,
2743                                      ExplodedNode* Pred, ExplodedNodeSet& Dst) {
2744   if (I == E) {
2745     VisitAsmStmtHelperInputs(A, A->begin_inputs(), A->end_inputs(), Pred, Dst);
2746     return;
2747   }
2748 
2749   ExplodedNodeSet Tmp;
2750   Visit(*I, Pred, Tmp);
2751   ++I;
2752 
2753   for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end();NI != NE;++NI)
2754     VisitAsmStmtHelperOutputs(A, I, E, *NI, Dst);
2755 }
2756 
2757 void ExprEngine::VisitAsmStmtHelperInputs(const AsmStmt* A,
2758                                             AsmStmt::const_inputs_iterator I,
2759                                             AsmStmt::const_inputs_iterator E,
2760                                             ExplodedNode* Pred,
2761                                             ExplodedNodeSet& Dst) {
2762   if (I == E) {
2763 
2764     // We have processed both the inputs and the outputs.  All of the outputs
2765     // should evaluate to Locs.  Nuke all of their values.
2766 
2767     // FIXME: Some day in the future it would be nice to allow a "plug-in"
2768     // which interprets the inline asm and stores proper results in the
2769     // outputs.
2770 
2771     const GRState* state = GetState(Pred);
2772 
2773     for (AsmStmt::const_outputs_iterator OI = A->begin_outputs(),
2774                                    OE = A->end_outputs(); OI != OE; ++OI) {
2775 
2776       SVal X = state->getSVal(*OI);
2777       assert (!isa<NonLoc>(X));  // Should be an Lval, or unknown, undef.
2778 
2779       if (isa<Loc>(X))
2780         state = state->bindLoc(cast<Loc>(X), UnknownVal());
2781     }
2782 
2783     MakeNode(Dst, A, Pred, state);
2784     return;
2785   }
2786 
2787   ExplodedNodeSet Tmp;
2788   Visit(*I, Pred, Tmp);
2789 
2790   ++I;
2791 
2792   for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end(); NI!=NE; ++NI)
2793     VisitAsmStmtHelperInputs(A, I, E, *NI, Dst);
2794 }
2795 
2796 void ExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred,
2797                                    ExplodedNodeSet &Dst) {
2798   ExplodedNodeSet Src;
2799   if (const Expr *RetE = RS->getRetValue()) {
2800     // Record the returned expression in the state. It will be used in
2801     // processCallExit to bind the return value to the call expr.
2802     {
2803       static int tag = 0;
2804       const GRState *state = GetState(Pred);
2805       state = state->set<ReturnExpr>(RetE);
2806       Pred = Builder->generateNode(RetE, state, Pred, &tag);
2807     }
2808     // We may get a NULL Pred because we generated a cached node.
2809     if (Pred)
2810       Visit(RetE, Pred, Src);
2811   }
2812   else {
2813     Src.Add(Pred);
2814   }
2815 
2816   ExplodedNodeSet CheckedSet;
2817   getCheckerManager().runCheckersForPreStmt(CheckedSet, Src, RS, *this);
2818 
2819   for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
2820        I != E; ++I) {
2821 
2822     assert(Builder && "StmtNodeBuilder must be defined.");
2823 
2824     Pred = *I;
2825     unsigned size = Dst.size();
2826 
2827     SaveAndRestore<bool> OldSink(Builder->BuildSinks);
2828     SaveOr OldHasGen(Builder->hasGeneratedNode);
2829 
2830     getTF().evalReturn(Dst, *this, *Builder, RS, Pred);
2831 
2832     // Handle the case where no nodes where generated.
2833     if (!Builder->BuildSinks && Dst.size() == size &&
2834         !Builder->hasGeneratedNode)
2835       MakeNode(Dst, RS, Pred, GetState(Pred));
2836   }
2837 }
2838 
2839 //===----------------------------------------------------------------------===//
2840 // Transfer functions: Binary operators.
2841 //===----------------------------------------------------------------------===//
2842 
2843 void ExprEngine::VisitBinaryOperator(const BinaryOperator* B,
2844                                        ExplodedNode* Pred,
2845                                        ExplodedNodeSet& Dst) {
2846   ExplodedNodeSet Tmp1;
2847   Expr* LHS = B->getLHS()->IgnoreParens();
2848   Expr* RHS = B->getRHS()->IgnoreParens();
2849 
2850   Visit(LHS, Pred, Tmp1);
2851   ExplodedNodeSet Tmp3;
2852 
2853   for (ExplodedNodeSet::iterator I1=Tmp1.begin(), E1=Tmp1.end(); I1!=E1; ++I1) {
2854     SVal LeftV = GetState(*I1)->getSVal(LHS);
2855     ExplodedNodeSet Tmp2;
2856     Visit(RHS, *I1, Tmp2);
2857 
2858     ExplodedNodeSet CheckedSet;
2859     getCheckerManager().runCheckersForPreStmt(CheckedSet, Tmp2, B, *this);
2860 
2861     // With both the LHS and RHS evaluated, process the operation itself.
2862 
2863     for (ExplodedNodeSet::iterator I2=CheckedSet.begin(), E2=CheckedSet.end();
2864          I2 != E2; ++I2) {
2865 
2866       const GRState *state = GetState(*I2);
2867       SVal RightV = state->getSVal(RHS);
2868 
2869       BinaryOperator::Opcode Op = B->getOpcode();
2870 
2871       if (Op == BO_Assign) {
2872         // EXPERIMENTAL: "Conjured" symbols.
2873         // FIXME: Handle structs.
2874         if (RightV.isUnknown() ||!getConstraintManager().canReasonAbout(RightV))
2875         {
2876           unsigned Count = Builder->getCurrentBlockCount();
2877           RightV = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), Count);
2878         }
2879 
2880         SVal ExprVal = B->isLValue() ? LeftV : RightV;
2881 
2882         // Simulate the effects of a "store":  bind the value of the RHS
2883         // to the L-Value represented by the LHS.
2884         evalStore(Tmp3, B, LHS, *I2, state->BindExpr(B, ExprVal), LeftV,RightV);
2885         continue;
2886       }
2887 
2888       if (!B->isAssignmentOp()) {
2889         // Process non-assignments except commas or short-circuited
2890         // logical expressions (LAnd and LOr).
2891         SVal Result = evalBinOp(state, Op, LeftV, RightV, B->getType());
2892 
2893         if (Result.isUnknown()) {
2894           MakeNode(Tmp3, B, *I2, state);
2895           continue;
2896         }
2897 
2898         state = state->BindExpr(B, Result);
2899 
2900         MakeNode(Tmp3, B, *I2, state);
2901         continue;
2902       }
2903 
2904       assert (B->isCompoundAssignmentOp());
2905 
2906       switch (Op) {
2907         default:
2908           assert(0 && "Invalid opcode for compound assignment.");
2909         case BO_MulAssign: Op = BO_Mul; break;
2910         case BO_DivAssign: Op = BO_Div; break;
2911         case BO_RemAssign: Op = BO_Rem; break;
2912         case BO_AddAssign: Op = BO_Add; break;
2913         case BO_SubAssign: Op = BO_Sub; break;
2914         case BO_ShlAssign: Op = BO_Shl; break;
2915         case BO_ShrAssign: Op = BO_Shr; break;
2916         case BO_AndAssign: Op = BO_And; break;
2917         case BO_XorAssign: Op = BO_Xor; break;
2918         case BO_OrAssign:  Op = BO_Or;  break;
2919       }
2920 
2921       // Perform a load (the LHS).  This performs the checks for
2922       // null dereferences, and so on.
2923       ExplodedNodeSet Tmp4;
2924       SVal location = state->getSVal(LHS);
2925       evalLoad(Tmp4, LHS, *I2, state, location);
2926 
2927       for (ExplodedNodeSet::iterator I4=Tmp4.begin(), E4=Tmp4.end(); I4!=E4;
2928            ++I4) {
2929         state = GetState(*I4);
2930         SVal V = state->getSVal(LHS);
2931 
2932         // Get the computation type.
2933         QualType CTy =
2934           cast<CompoundAssignOperator>(B)->getComputationResultType();
2935         CTy = getContext().getCanonicalType(CTy);
2936 
2937         QualType CLHSTy =
2938           cast<CompoundAssignOperator>(B)->getComputationLHSType();
2939         CLHSTy = getContext().getCanonicalType(CLHSTy);
2940 
2941         QualType LTy = getContext().getCanonicalType(LHS->getType());
2942 
2943         // Promote LHS.
2944         V = svalBuilder.evalCast(V, CLHSTy, LTy);
2945 
2946         // Compute the result of the operation.
2947         SVal Result = svalBuilder.evalCast(evalBinOp(state, Op, V, RightV, CTy),
2948                                       B->getType(), CTy);
2949 
2950         // EXPERIMENTAL: "Conjured" symbols.
2951         // FIXME: Handle structs.
2952 
2953         SVal LHSVal;
2954 
2955         if (Result.isUnknown() ||
2956             !getConstraintManager().canReasonAbout(Result)) {
2957 
2958           unsigned Count = Builder->getCurrentBlockCount();
2959 
2960           // The symbolic value is actually for the type of the left-hand side
2961           // expression, not the computation type, as this is the value the
2962           // LValue on the LHS will bind to.
2963           LHSVal = svalBuilder.getConjuredSymbolVal(NULL, B->getRHS(), LTy, Count);
2964 
2965           // However, we need to convert the symbol to the computation type.
2966           Result = svalBuilder.evalCast(LHSVal, CTy, LTy);
2967         }
2968         else {
2969           // The left-hand side may bind to a different value then the
2970           // computation type.
2971           LHSVal = svalBuilder.evalCast(Result, LTy, CTy);
2972         }
2973 
2974         // In C++, assignment and compound assignment operators return an
2975         // lvalue.
2976         if (B->isLValue())
2977           state = state->BindExpr(B, location);
2978         else
2979           state = state->BindExpr(B, Result);
2980 
2981         evalStore(Tmp3, B, LHS, *I4, state, location, LHSVal);
2982       }
2983     }
2984   }
2985 
2986   getCheckerManager().runCheckersForPostStmt(Dst, Tmp3, B, *this);
2987 }
2988 
2989 //===----------------------------------------------------------------------===//
2990 // Visualization.
2991 //===----------------------------------------------------------------------===//
2992 
2993 #ifndef NDEBUG
2994 static ExprEngine* GraphPrintCheckerState;
2995 static SourceManager* GraphPrintSourceManager;
2996 
2997 namespace llvm {
2998 template<>
2999 struct DOTGraphTraits<ExplodedNode*> :
3000   public DefaultDOTGraphTraits {
3001 
3002   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
3003 
3004   // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
3005   // work.
3006   static std::string getNodeAttributes(const ExplodedNode* N, void*) {
3007 
3008 #if 0
3009       // FIXME: Replace with a general scheme to tell if the node is
3010       // an error node.
3011     if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
3012         GraphPrintCheckerState->isExplicitNullDeref(N) ||
3013         GraphPrintCheckerState->isUndefDeref(N) ||
3014         GraphPrintCheckerState->isUndefStore(N) ||
3015         GraphPrintCheckerState->isUndefControlFlow(N) ||
3016         GraphPrintCheckerState->isUndefResult(N) ||
3017         GraphPrintCheckerState->isBadCall(N) ||
3018         GraphPrintCheckerState->isUndefArg(N))
3019       return "color=\"red\",style=\"filled\"";
3020 
3021     if (GraphPrintCheckerState->isNoReturnCall(N))
3022       return "color=\"blue\",style=\"filled\"";
3023 #endif
3024     return "";
3025   }
3026 
3027   static std::string getNodeLabel(const ExplodedNode* N, void*){
3028 
3029     std::string sbuf;
3030     llvm::raw_string_ostream Out(sbuf);
3031 
3032     // Program Location.
3033     ProgramPoint Loc = N->getLocation();
3034 
3035     switch (Loc.getKind()) {
3036       case ProgramPoint::BlockEntranceKind:
3037         Out << "Block Entrance: B"
3038             << cast<BlockEntrance>(Loc).getBlock()->getBlockID();
3039         break;
3040 
3041       case ProgramPoint::BlockExitKind:
3042         assert (false);
3043         break;
3044 
3045       case ProgramPoint::CallEnterKind:
3046         Out << "CallEnter";
3047         break;
3048 
3049       case ProgramPoint::CallExitKind:
3050         Out << "CallExit";
3051         break;
3052 
3053       default: {
3054         if (StmtPoint *L = dyn_cast<StmtPoint>(&Loc)) {
3055           const Stmt* S = L->getStmt();
3056           SourceLocation SLoc = S->getLocStart();
3057 
3058           Out << S->getStmtClassName() << ' ' << (void*) S << ' ';
3059           LangOptions LO; // FIXME.
3060           S->printPretty(Out, 0, PrintingPolicy(LO));
3061 
3062           if (SLoc.isFileID()) {
3063             Out << "\\lline="
3064               << GraphPrintSourceManager->getInstantiationLineNumber(SLoc)
3065               << " col="
3066               << GraphPrintSourceManager->getInstantiationColumnNumber(SLoc)
3067               << "\\l";
3068           }
3069 
3070           if (isa<PreStmt>(Loc))
3071             Out << "\\lPreStmt\\l;";
3072           else if (isa<PostLoad>(Loc))
3073             Out << "\\lPostLoad\\l;";
3074           else if (isa<PostStore>(Loc))
3075             Out << "\\lPostStore\\l";
3076           else if (isa<PostLValue>(Loc))
3077             Out << "\\lPostLValue\\l";
3078 
3079 #if 0
3080             // FIXME: Replace with a general scheme to determine
3081             // the name of the check.
3082           if (GraphPrintCheckerState->isImplicitNullDeref(N))
3083             Out << "\\|Implicit-Null Dereference.\\l";
3084           else if (GraphPrintCheckerState->isExplicitNullDeref(N))
3085             Out << "\\|Explicit-Null Dereference.\\l";
3086           else if (GraphPrintCheckerState->isUndefDeref(N))
3087             Out << "\\|Dereference of undefialied value.\\l";
3088           else if (GraphPrintCheckerState->isUndefStore(N))
3089             Out << "\\|Store to Undefined Loc.";
3090           else if (GraphPrintCheckerState->isUndefResult(N))
3091             Out << "\\|Result of operation is undefined.";
3092           else if (GraphPrintCheckerState->isNoReturnCall(N))
3093             Out << "\\|Call to function marked \"noreturn\".";
3094           else if (GraphPrintCheckerState->isBadCall(N))
3095             Out << "\\|Call to NULL/Undefined.";
3096           else if (GraphPrintCheckerState->isUndefArg(N))
3097             Out << "\\|Argument in call is undefined";
3098 #endif
3099 
3100           break;
3101         }
3102 
3103         const BlockEdge& E = cast<BlockEdge>(Loc);
3104         Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
3105             << E.getDst()->getBlockID()  << ')';
3106 
3107         if (const Stmt* T = E.getSrc()->getTerminator()) {
3108 
3109           SourceLocation SLoc = T->getLocStart();
3110 
3111           Out << "\\|Terminator: ";
3112           LangOptions LO; // FIXME.
3113           E.getSrc()->printTerminator(Out, LO);
3114 
3115           if (SLoc.isFileID()) {
3116             Out << "\\lline="
3117               << GraphPrintSourceManager->getInstantiationLineNumber(SLoc)
3118               << " col="
3119               << GraphPrintSourceManager->getInstantiationColumnNumber(SLoc);
3120           }
3121 
3122           if (isa<SwitchStmt>(T)) {
3123             const Stmt* Label = E.getDst()->getLabel();
3124 
3125             if (Label) {
3126               if (const CaseStmt* C = dyn_cast<CaseStmt>(Label)) {
3127                 Out << "\\lcase ";
3128                 LangOptions LO; // FIXME.
3129                 C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO));
3130 
3131                 if (const Stmt* RHS = C->getRHS()) {
3132                   Out << " .. ";
3133                   RHS->printPretty(Out, 0, PrintingPolicy(LO));
3134                 }
3135 
3136                 Out << ":";
3137               }
3138               else {
3139                 assert (isa<DefaultStmt>(Label));
3140                 Out << "\\ldefault:";
3141               }
3142             }
3143             else
3144               Out << "\\l(implicit) default:";
3145           }
3146           else if (isa<IndirectGotoStmt>(T)) {
3147             // FIXME
3148           }
3149           else {
3150             Out << "\\lCondition: ";
3151             if (*E.getSrc()->succ_begin() == E.getDst())
3152               Out << "true";
3153             else
3154               Out << "false";
3155           }
3156 
3157           Out << "\\l";
3158         }
3159 
3160 #if 0
3161           // FIXME: Replace with a general scheme to determine
3162           // the name of the check.
3163         if (GraphPrintCheckerState->isUndefControlFlow(N)) {
3164           Out << "\\|Control-flow based on\\lUndefined value.\\l";
3165         }
3166 #endif
3167       }
3168     }
3169 
3170     const GRState *state = N->getState();
3171     Out << "\\|StateID: " << (void*) state
3172         << " NodeID: " << (void*) N << "\\|";
3173     state->printDOT(Out, *N->getLocationContext()->getCFG());
3174     Out << "\\l";
3175     return Out.str();
3176   }
3177 };
3178 } // end llvm namespace
3179 #endif
3180 
3181 #ifndef NDEBUG
3182 template <typename ITERATOR>
3183 ExplodedNode* GetGraphNode(ITERATOR I) { return *I; }
3184 
3185 template <> ExplodedNode*
3186 GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator>
3187   (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) {
3188   return I->first;
3189 }
3190 #endif
3191 
3192 void ExprEngine::ViewGraph(bool trim) {
3193 #ifndef NDEBUG
3194   if (trim) {
3195     std::vector<ExplodedNode*> Src;
3196 
3197     // Flush any outstanding reports to make sure we cover all the nodes.
3198     // This does not cause them to get displayed.
3199     for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
3200       const_cast<BugType*>(*I)->FlushReports(BR);
3201 
3202     // Iterate through the reports and get their nodes.
3203     for (BugReporter::EQClasses_iterator
3204            EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
3205       BugReportEquivClass& EQ = *EI;
3206       const BugReport &R = **EQ.begin();
3207       ExplodedNode *N = const_cast<ExplodedNode*>(R.getErrorNode());
3208       if (N) Src.push_back(N);
3209     }
3210 
3211     ViewGraph(&Src[0], &Src[0]+Src.size());
3212   }
3213   else {
3214     GraphPrintCheckerState = this;
3215     GraphPrintSourceManager = &getContext().getSourceManager();
3216 
3217     llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
3218 
3219     GraphPrintCheckerState = NULL;
3220     GraphPrintSourceManager = NULL;
3221   }
3222 #endif
3223 }
3224 
3225 void ExprEngine::ViewGraph(ExplodedNode** Beg, ExplodedNode** End) {
3226 #ifndef NDEBUG
3227   GraphPrintCheckerState = this;
3228   GraphPrintSourceManager = &getContext().getSourceManager();
3229 
3230   std::auto_ptr<ExplodedGraph> TrimmedG(G.Trim(Beg, End).first);
3231 
3232   if (!TrimmedG.get())
3233     llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
3234   else
3235     llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
3236 
3237   GraphPrintCheckerState = NULL;
3238   GraphPrintSourceManager = NULL;
3239 #endif
3240 }
3241