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