ExprEngine.cpp 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930
  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. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  16. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  17. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  18. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  19. #include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
  20. #include "clang/AST/CharUnits.h"
  21. #include "clang/AST/ParentMap.h"
  22. #include "clang/AST/StmtObjC.h"
  23. #include "clang/AST/DeclCXX.h"
  24. #include "clang/Basic/Builtins.h"
  25. #include "clang/Basic/SourceManager.h"
  26. #include "clang/Basic/PrettyStackTrace.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include "llvm/ADT/ImmutableList.h"
  29. #ifndef NDEBUG
  30. #include "llvm/Support/GraphWriter.h"
  31. #endif
  32. using namespace clang;
  33. using namespace ento;
  34. using llvm::APSInt;
  35. //===----------------------------------------------------------------------===//
  36. // Utility functions.
  37. //===----------------------------------------------------------------------===//
  38. static inline Selector GetNullarySelector(const char* name, ASTContext &Ctx) {
  39. IdentifierInfo* II = &Ctx.Idents.get(name);
  40. return Ctx.Selectors.getSelector(0, &II);
  41. }
  42. //===----------------------------------------------------------------------===//
  43. // Engine construction and deletion.
  44. //===----------------------------------------------------------------------===//
  45. ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled)
  46. : AMgr(mgr),
  47. AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
  48. Engine(*this),
  49. G(Engine.getGraph()),
  50. StateMgr(getContext(), mgr.getStoreManagerCreator(),
  51. mgr.getConstraintManagerCreator(), G.getAllocator(),
  52. *this),
  53. SymMgr(StateMgr.getSymbolManager()),
  54. svalBuilder(StateMgr.getSValBuilder()),
  55. EntryNode(NULL),
  56. currentStmt(NULL), currentStmtIdx(0), currentBuilderContext(0),
  57. NSExceptionII(NULL), NSExceptionInstanceRaiseSelectors(NULL),
  58. RaiseSel(GetNullarySelector("raise", getContext())),
  59. ObjCGCEnabled(gcEnabled), BR(mgr, *this) {
  60. if (mgr.shouldEagerlyTrimExplodedGraph()) {
  61. // Enable eager node reclaimation when constructing the ExplodedGraph.
  62. G.enableNodeReclamation();
  63. }
  64. }
  65. ExprEngine::~ExprEngine() {
  66. BR.FlushReports();
  67. delete [] NSExceptionInstanceRaiseSelectors;
  68. }
  69. //===----------------------------------------------------------------------===//
  70. // Utility methods.
  71. //===----------------------------------------------------------------------===//
  72. ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
  73. ProgramStateRef state = StateMgr.getInitialState(InitLoc);
  74. const Decl *D = InitLoc->getDecl();
  75. // Preconditions.
  76. // FIXME: It would be nice if we had a more general mechanism to add
  77. // such preconditions. Some day.
  78. do {
  79. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  80. // Precondition: the first argument of 'main' is an integer guaranteed
  81. // to be > 0.
  82. const IdentifierInfo *II = FD->getIdentifier();
  83. if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
  84. break;
  85. const ParmVarDecl *PD = FD->getParamDecl(0);
  86. QualType T = PD->getType();
  87. if (!T->isIntegerType())
  88. break;
  89. const MemRegion *R = state->getRegion(PD, InitLoc);
  90. if (!R)
  91. break;
  92. SVal V = state->getSVal(loc::MemRegionVal(R));
  93. SVal Constraint_untested = evalBinOp(state, BO_GT, V,
  94. svalBuilder.makeZeroVal(T),
  95. getContext().IntTy);
  96. DefinedOrUnknownSVal *Constraint =
  97. dyn_cast<DefinedOrUnknownSVal>(&Constraint_untested);
  98. if (!Constraint)
  99. break;
  100. if (ProgramStateRef newState = state->assume(*Constraint, true))
  101. state = newState;
  102. }
  103. break;
  104. }
  105. while (0);
  106. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  107. // Precondition: 'self' is always non-null upon entry to an Objective-C
  108. // method.
  109. const ImplicitParamDecl *SelfD = MD->getSelfDecl();
  110. const MemRegion *R = state->getRegion(SelfD, InitLoc);
  111. SVal V = state->getSVal(loc::MemRegionVal(R));
  112. if (const Loc *LV = dyn_cast<Loc>(&V)) {
  113. // Assume that the pointer value in 'self' is non-null.
  114. state = state->assume(*LV, true);
  115. assert(state && "'self' cannot be null");
  116. }
  117. }
  118. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  119. if (!MD->isStatic()) {
  120. // Precondition: 'this' is always non-null upon entry to the
  121. // top-level function. This is our starting assumption for
  122. // analyzing an "open" program.
  123. const StackFrameContext *SFC = InitLoc->getCurrentStackFrame();
  124. if (SFC->getParent() == 0) {
  125. loc::MemRegionVal L(getCXXThisRegion(MD, SFC));
  126. SVal V = state->getSVal(L);
  127. if (const Loc *LV = dyn_cast<Loc>(&V)) {
  128. state = state->assume(*LV, true);
  129. assert(state && "'this' cannot be null");
  130. }
  131. }
  132. }
  133. }
  134. return state;
  135. }
  136. //===----------------------------------------------------------------------===//
  137. // Top-level transfer function logic (Dispatcher).
  138. //===----------------------------------------------------------------------===//
  139. /// evalAssume - Called by ConstraintManager. Used to call checker-specific
  140. /// logic for handling assumptions on symbolic values.
  141. ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
  142. SVal cond, bool assumption) {
  143. return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
  144. }
  145. bool ExprEngine::wantsRegionChangeUpdate(ProgramStateRef state) {
  146. return getCheckerManager().wantsRegionChangeUpdate(state);
  147. }
  148. ProgramStateRef
  149. ExprEngine::processRegionChanges(ProgramStateRef state,
  150. const StoreManager::InvalidatedSymbols *invalidated,
  151. ArrayRef<const MemRegion *> Explicits,
  152. ArrayRef<const MemRegion *> Regions) {
  153. return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
  154. Explicits, Regions);
  155. }
  156. void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
  157. const char *NL, const char *Sep) {
  158. getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
  159. }
  160. void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
  161. getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
  162. }
  163. void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
  164. unsigned StmtIdx, NodeBuilderContext *Ctx) {
  165. currentStmtIdx = StmtIdx;
  166. currentBuilderContext = Ctx;
  167. switch (E.getKind()) {
  168. case CFGElement::Invalid:
  169. llvm_unreachable("Unexpected CFGElement kind.");
  170. case CFGElement::Statement:
  171. ProcessStmt(const_cast<Stmt*>(E.getAs<CFGStmt>()->getStmt()), Pred);
  172. return;
  173. case CFGElement::Initializer:
  174. ProcessInitializer(E.getAs<CFGInitializer>()->getInitializer(), Pred);
  175. return;
  176. case CFGElement::AutomaticObjectDtor:
  177. case CFGElement::BaseDtor:
  178. case CFGElement::MemberDtor:
  179. case CFGElement::TemporaryDtor:
  180. ProcessImplicitDtor(*E.getAs<CFGImplicitDtor>(), Pred);
  181. return;
  182. }
  183. }
  184. static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
  185. const CFGStmt S,
  186. const ExplodedNode *Pred,
  187. const LocationContext *LC) {
  188. // Are we never purging state values?
  189. if (AMgr.getPurgeMode() == PurgeNone)
  190. return false;
  191. // Is this the beginning of a basic block?
  192. if (isa<BlockEntrance>(Pred->getLocation()))
  193. return true;
  194. // Is this on a non-expression?
  195. if (!isa<Expr>(S.getStmt()))
  196. return true;
  197. // Is this an expression that is consumed by another expression? If so,
  198. // postpone cleaning out the state.
  199. ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
  200. return !PM.isConsumedExpr(cast<Expr>(S.getStmt()));
  201. }
  202. void ExprEngine::ProcessStmt(const CFGStmt S,
  203. ExplodedNode *Pred) {
  204. // Reclaim any unnecessary nodes in the ExplodedGraph.
  205. G.reclaimRecentlyAllocatedNodes();
  206. currentStmt = S.getStmt();
  207. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  208. currentStmt->getLocStart(),
  209. "Error evaluating statement");
  210. EntryNode = Pred;
  211. ProgramStateRef EntryState = EntryNode->getState();
  212. CleanedState = EntryState;
  213. // Create the cleaned state.
  214. const LocationContext *LC = EntryNode->getLocationContext();
  215. SymbolReaper SymReaper(LC, currentStmt, SymMgr, getStoreManager());
  216. if (shouldRemoveDeadBindings(AMgr, S, Pred, LC)) {
  217. getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
  218. const StackFrameContext *SFC = LC->getCurrentStackFrame();
  219. // Create a state in which dead bindings are removed from the environment
  220. // and the store. TODO: The function should just return new env and store,
  221. // not a new state.
  222. CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
  223. }
  224. // Process any special transfer function for dead symbols.
  225. ExplodedNodeSet Tmp;
  226. // A tag to track convenience transitions, which can be removed at cleanup.
  227. static SimpleProgramPointTag cleanupTag("ExprEngine : Clean Node");
  228. if (!SymReaper.hasDeadSymbols()) {
  229. // Generate a CleanedNode that has the environment and store cleaned
  230. // up. Since no symbols are dead, we can optimize and not clean out
  231. // the constraint manager.
  232. StmtNodeBuilder Bldr(Pred, Tmp, *currentBuilderContext);
  233. Bldr.generateNode(currentStmt, EntryNode, CleanedState, false, &cleanupTag);
  234. } else {
  235. // Call checkers with the non-cleaned state so that they could query the
  236. // values of the soon to be dead symbols.
  237. ExplodedNodeSet CheckedSet;
  238. getCheckerManager().runCheckersForDeadSymbols(CheckedSet, EntryNode,
  239. SymReaper, currentStmt, *this);
  240. // For each node in CheckedSet, generate CleanedNodes that have the
  241. // environment, the store, and the constraints cleaned up but have the
  242. // user-supplied states as the predecessors.
  243. StmtNodeBuilder Bldr(CheckedSet, Tmp, *currentBuilderContext);
  244. for (ExplodedNodeSet::const_iterator
  245. I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) {
  246. ProgramStateRef CheckerState = (*I)->getState();
  247. // The constraint manager has not been cleaned up yet, so clean up now.
  248. CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
  249. SymReaper);
  250. assert(StateMgr.haveEqualEnvironments(CheckerState, EntryState) &&
  251. "Checkers are not allowed to modify the Environment as a part of "
  252. "checkDeadSymbols processing.");
  253. assert(StateMgr.haveEqualStores(CheckerState, EntryState) &&
  254. "Checkers are not allowed to modify the Store as a part of "
  255. "checkDeadSymbols processing.");
  256. // Create a state based on CleanedState with CheckerState GDM and
  257. // generate a transition to that state.
  258. ProgramStateRef CleanedCheckerSt =
  259. StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
  260. Bldr.generateNode(currentStmt, *I, CleanedCheckerSt, false, &cleanupTag,
  261. ProgramPoint::PostPurgeDeadSymbolsKind);
  262. }
  263. }
  264. ExplodedNodeSet Dst;
  265. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end(); I!=E; ++I) {
  266. ExplodedNodeSet DstI;
  267. // Visit the statement.
  268. Visit(currentStmt, *I, DstI);
  269. Dst.insert(DstI);
  270. }
  271. // Enqueue the new nodes onto the work list.
  272. Engine.enqueue(Dst, currentBuilderContext->getBlock(), currentStmtIdx);
  273. // NULL out these variables to cleanup.
  274. CleanedState = NULL;
  275. EntryNode = NULL;
  276. currentStmt = 0;
  277. }
  278. void ExprEngine::ProcessInitializer(const CFGInitializer Init,
  279. ExplodedNode *Pred) {
  280. ExplodedNodeSet Dst;
  281. // We don't set EntryNode and currentStmt. And we don't clean up state.
  282. const CXXCtorInitializer *BMI = Init.getInitializer();
  283. const StackFrameContext *stackFrame =
  284. cast<StackFrameContext>(Pred->getLocationContext());
  285. const CXXConstructorDecl *decl =
  286. cast<CXXConstructorDecl>(stackFrame->getDecl());
  287. const CXXThisRegion *thisReg = getCXXThisRegion(decl, stackFrame);
  288. SVal thisVal = Pred->getState()->getSVal(thisReg);
  289. if (BMI->isAnyMemberInitializer()) {
  290. ExplodedNodeSet AfterEval;
  291. // Evaluate the initializer.
  292. Visit(BMI->getInit(), Pred, AfterEval);
  293. StmtNodeBuilder Bldr(AfterEval, Dst, *currentBuilderContext);
  294. for (ExplodedNodeSet::iterator I = AfterEval.begin(),
  295. E = AfterEval.end(); I != E; ++I){
  296. ExplodedNode *P = *I;
  297. ProgramStateRef state = P->getState();
  298. const FieldDecl *FD = BMI->getAnyMember();
  299. SVal FieldLoc = state->getLValue(FD, thisVal);
  300. SVal InitVal = state->getSVal(BMI->getInit(), Pred->getLocationContext());
  301. state = state->bindLoc(FieldLoc, InitVal);
  302. // Use a custom node building process.
  303. PostInitializer PP(BMI, stackFrame);
  304. // Builder automatically add the generated node to the deferred set,
  305. // which are processed in the builder's dtor.
  306. Bldr.generateNode(PP, P, state);
  307. }
  308. } else {
  309. assert(BMI->isBaseInitializer());
  310. // Get the base class declaration.
  311. const CXXConstructExpr *ctorExpr = cast<CXXConstructExpr>(BMI->getInit());
  312. // Create the base object region.
  313. SVal baseVal =
  314. getStoreManager().evalDerivedToBase(thisVal, ctorExpr->getType());
  315. const MemRegion *baseReg = baseVal.getAsRegion();
  316. assert(baseReg);
  317. VisitCXXConstructExpr(ctorExpr, baseReg, Pred, Dst);
  318. }
  319. // Enqueue the new nodes onto the work list.
  320. Engine.enqueue(Dst, currentBuilderContext->getBlock(), currentStmtIdx);
  321. }
  322. void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
  323. ExplodedNode *Pred) {
  324. ExplodedNodeSet Dst;
  325. switch (D.getKind()) {
  326. case CFGElement::AutomaticObjectDtor:
  327. ProcessAutomaticObjDtor(cast<CFGAutomaticObjDtor>(D), Pred, Dst);
  328. break;
  329. case CFGElement::BaseDtor:
  330. ProcessBaseDtor(cast<CFGBaseDtor>(D), Pred, Dst);
  331. break;
  332. case CFGElement::MemberDtor:
  333. ProcessMemberDtor(cast<CFGMemberDtor>(D), Pred, Dst);
  334. break;
  335. case CFGElement::TemporaryDtor:
  336. ProcessTemporaryDtor(cast<CFGTemporaryDtor>(D), Pred, Dst);
  337. break;
  338. default:
  339. llvm_unreachable("Unexpected dtor kind.");
  340. }
  341. // Enqueue the new nodes onto the work list.
  342. Engine.enqueue(Dst, currentBuilderContext->getBlock(), currentStmtIdx);
  343. }
  344. void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
  345. ExplodedNode *Pred,
  346. ExplodedNodeSet &Dst) {
  347. ProgramStateRef state = Pred->getState();
  348. const VarDecl *varDecl = Dtor.getVarDecl();
  349. QualType varType = varDecl->getType();
  350. if (const ReferenceType *refType = varType->getAs<ReferenceType>())
  351. varType = refType->getPointeeType();
  352. const CXXRecordDecl *recordDecl = varType->getAsCXXRecordDecl();
  353. assert(recordDecl && "get CXXRecordDecl fail");
  354. const CXXDestructorDecl *dtorDecl = recordDecl->getDestructor();
  355. Loc dest = state->getLValue(varDecl, Pred->getLocationContext());
  356. VisitCXXDestructor(dtorDecl, cast<loc::MemRegionVal>(dest).getRegion(),
  357. Dtor.getTriggerStmt(), Pred, Dst);
  358. }
  359. void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
  360. ExplodedNode *Pred, ExplodedNodeSet &Dst) {}
  361. void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
  362. ExplodedNode *Pred, ExplodedNodeSet &Dst) {}
  363. void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
  364. ExplodedNode *Pred,
  365. ExplodedNodeSet &Dst) {}
  366. void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
  367. ExplodedNodeSet &DstTop) {
  368. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  369. S->getLocStart(),
  370. "Error evaluating statement");
  371. ExplodedNodeSet Dst;
  372. StmtNodeBuilder Bldr(Pred, DstTop, *currentBuilderContext);
  373. // Expressions to ignore.
  374. if (const Expr *Ex = dyn_cast<Expr>(S))
  375. S = Ex->IgnoreParens();
  376. // FIXME: add metadata to the CFG so that we can disable
  377. // this check when we KNOW that there is no block-level subexpression.
  378. // The motivation is that this check requires a hashtable lookup.
  379. if (S != currentStmt && Pred->getLocationContext()->getCFG()->isBlkExpr(S))
  380. return;
  381. switch (S->getStmtClass()) {
  382. // C++ and ARC stuff we don't support yet.
  383. case Expr::ObjCIndirectCopyRestoreExprClass:
  384. case Stmt::CXXBindTemporaryExprClass:
  385. case Stmt::CXXCatchStmtClass:
  386. case Stmt::CXXDependentScopeMemberExprClass:
  387. case Stmt::CXXPseudoDestructorExprClass:
  388. case Stmt::CXXThrowExprClass:
  389. case Stmt::CXXTryStmtClass:
  390. case Stmt::CXXTypeidExprClass:
  391. case Stmt::CXXUuidofExprClass:
  392. case Stmt::CXXUnresolvedConstructExprClass:
  393. case Stmt::CXXScalarValueInitExprClass:
  394. case Stmt::DependentScopeDeclRefExprClass:
  395. case Stmt::UnaryTypeTraitExprClass:
  396. case Stmt::BinaryTypeTraitExprClass:
  397. case Stmt::ArrayTypeTraitExprClass:
  398. case Stmt::ExpressionTraitExprClass:
  399. case Stmt::UnresolvedLookupExprClass:
  400. case Stmt::UnresolvedMemberExprClass:
  401. case Stmt::CXXNoexceptExprClass:
  402. case Stmt::PackExpansionExprClass:
  403. case Stmt::SubstNonTypeTemplateParmPackExprClass:
  404. case Stmt::SEHTryStmtClass:
  405. case Stmt::SEHExceptStmtClass:
  406. case Stmt::LambdaExprClass:
  407. case Stmt::SEHFinallyStmtClass: {
  408. const ExplodedNode *node = Bldr.generateNode(S, Pred, Pred->getState());
  409. Engine.addAbortedBlock(node, currentBuilderContext->getBlock());
  410. break;
  411. }
  412. // We don't handle default arguments either yet, but we can fake it
  413. // for now by just skipping them.
  414. case Stmt::SubstNonTypeTemplateParmExprClass:
  415. case Stmt::CXXDefaultArgExprClass:
  416. break;
  417. case Stmt::ParenExprClass:
  418. llvm_unreachable("ParenExprs already handled.");
  419. case Stmt::GenericSelectionExprClass:
  420. llvm_unreachable("GenericSelectionExprs already handled.");
  421. // Cases that should never be evaluated simply because they shouldn't
  422. // appear in the CFG.
  423. case Stmt::BreakStmtClass:
  424. case Stmt::CaseStmtClass:
  425. case Stmt::CompoundStmtClass:
  426. case Stmt::ContinueStmtClass:
  427. case Stmt::CXXForRangeStmtClass:
  428. case Stmt::DefaultStmtClass:
  429. case Stmt::DoStmtClass:
  430. case Stmt::ForStmtClass:
  431. case Stmt::GotoStmtClass:
  432. case Stmt::IfStmtClass:
  433. case Stmt::IndirectGotoStmtClass:
  434. case Stmt::LabelStmtClass:
  435. case Stmt::NoStmtClass:
  436. case Stmt::NullStmtClass:
  437. case Stmt::SwitchStmtClass:
  438. case Stmt::WhileStmtClass:
  439. case Expr::MSDependentExistsStmtClass:
  440. llvm_unreachable("Stmt should not be in analyzer evaluation loop");
  441. case Stmt::GNUNullExprClass: {
  442. // GNU __null is a pointer-width integer, not an actual pointer.
  443. ProgramStateRef state = Pred->getState();
  444. state = state->BindExpr(S, Pred->getLocationContext(),
  445. svalBuilder.makeIntValWithPtrWidth(0, false));
  446. Bldr.generateNode(S, Pred, state);
  447. break;
  448. }
  449. case Stmt::ObjCAtSynchronizedStmtClass:
  450. Bldr.takeNodes(Pred);
  451. VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
  452. Bldr.addNodes(Dst);
  453. break;
  454. case Stmt::ObjCPropertyRefExprClass:
  455. // Implicitly handled by Environment::getSVal().
  456. break;
  457. case Stmt::ImplicitValueInitExprClass: {
  458. ProgramStateRef state = Pred->getState();
  459. QualType ty = cast<ImplicitValueInitExpr>(S)->getType();
  460. SVal val = svalBuilder.makeZeroVal(ty);
  461. Bldr.generateNode(S, Pred, state->BindExpr(S, Pred->getLocationContext(),
  462. val));
  463. break;
  464. }
  465. case Stmt::ExprWithCleanupsClass:
  466. Bldr.takeNodes(Pred);
  467. Visit(cast<ExprWithCleanups>(S)->getSubExpr(), Pred, Dst);
  468. Bldr.addNodes(Dst);
  469. break;
  470. // Cases not handled yet; but will handle some day.
  471. case Stmt::DesignatedInitExprClass:
  472. case Stmt::ExtVectorElementExprClass:
  473. case Stmt::ImaginaryLiteralClass:
  474. case Stmt::ObjCAtCatchStmtClass:
  475. case Stmt::ObjCAtFinallyStmtClass:
  476. case Stmt::ObjCAtTryStmtClass:
  477. case Stmt::ObjCAutoreleasePoolStmtClass:
  478. case Stmt::ObjCEncodeExprClass:
  479. case Stmt::ObjCIsaExprClass:
  480. case Stmt::ObjCProtocolExprClass:
  481. case Stmt::ObjCSelectorExprClass:
  482. case Stmt::ObjCStringLiteralClass:
  483. case Stmt::ParenListExprClass:
  484. case Stmt::PredefinedExprClass:
  485. case Stmt::ShuffleVectorExprClass:
  486. case Stmt::VAArgExprClass:
  487. case Stmt::CUDAKernelCallExprClass:
  488. case Stmt::OpaqueValueExprClass:
  489. case Stmt::AsTypeExprClass:
  490. case Stmt::AtomicExprClass:
  491. // Fall through.
  492. // Cases we intentionally don't evaluate, since they don't need
  493. // to be explicitly evaluated.
  494. case Stmt::AddrLabelExprClass:
  495. case Stmt::IntegerLiteralClass:
  496. case Stmt::CharacterLiteralClass:
  497. case Stmt::CXXBoolLiteralExprClass:
  498. case Stmt::FloatingLiteralClass:
  499. case Stmt::SizeOfPackExprClass:
  500. case Stmt::CXXNullPtrLiteralExprClass:
  501. // No-op. Simply propagate the current state unchanged.
  502. break;
  503. case Stmt::ArraySubscriptExprClass:
  504. Bldr.takeNodes(Pred);
  505. VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
  506. Bldr.addNodes(Dst);
  507. break;
  508. case Stmt::AsmStmtClass:
  509. Bldr.takeNodes(Pred);
  510. VisitAsmStmt(cast<AsmStmt>(S), Pred, Dst);
  511. Bldr.addNodes(Dst);
  512. break;
  513. case Stmt::BlockDeclRefExprClass: {
  514. Bldr.takeNodes(Pred);
  515. const BlockDeclRefExpr *BE = cast<BlockDeclRefExpr>(S);
  516. VisitCommonDeclRefExpr(BE, BE->getDecl(), Pred, Dst);
  517. Bldr.addNodes(Dst);
  518. break;
  519. }
  520. case Stmt::BlockExprClass:
  521. Bldr.takeNodes(Pred);
  522. VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
  523. Bldr.addNodes(Dst);
  524. break;
  525. case Stmt::BinaryOperatorClass: {
  526. const BinaryOperator* B = cast<BinaryOperator>(S);
  527. if (B->isLogicalOp()) {
  528. Bldr.takeNodes(Pred);
  529. VisitLogicalExpr(B, Pred, Dst);
  530. Bldr.addNodes(Dst);
  531. break;
  532. }
  533. else if (B->getOpcode() == BO_Comma) {
  534. ProgramStateRef state = Pred->getState();
  535. Bldr.generateNode(B, Pred,
  536. state->BindExpr(B, Pred->getLocationContext(),
  537. state->getSVal(B->getRHS(),
  538. Pred->getLocationContext())));
  539. break;
  540. }
  541. Bldr.takeNodes(Pred);
  542. if (AMgr.shouldEagerlyAssume() &&
  543. (B->isRelationalOp() || B->isEqualityOp())) {
  544. ExplodedNodeSet Tmp;
  545. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
  546. evalEagerlyAssume(Dst, Tmp, cast<Expr>(S));
  547. }
  548. else
  549. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  550. Bldr.addNodes(Dst);
  551. break;
  552. }
  553. case Stmt::CallExprClass:
  554. case Stmt::CXXOperatorCallExprClass:
  555. case Stmt::CXXMemberCallExprClass: {
  556. Bldr.takeNodes(Pred);
  557. VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
  558. Bldr.addNodes(Dst);
  559. break;
  560. }
  561. case Stmt::CXXTemporaryObjectExprClass:
  562. case Stmt::CXXConstructExprClass: {
  563. const CXXConstructExpr *C = cast<CXXConstructExpr>(S);
  564. // For block-level CXXConstructExpr, we don't have a destination region.
  565. // Let VisitCXXConstructExpr() create one.
  566. Bldr.takeNodes(Pred);
  567. VisitCXXConstructExpr(C, 0, Pred, Dst);
  568. Bldr.addNodes(Dst);
  569. break;
  570. }
  571. case Stmt::CXXNewExprClass: {
  572. Bldr.takeNodes(Pred);
  573. const CXXNewExpr *NE = cast<CXXNewExpr>(S);
  574. VisitCXXNewExpr(NE, Pred, Dst);
  575. Bldr.addNodes(Dst);
  576. break;
  577. }
  578. case Stmt::CXXDeleteExprClass: {
  579. Bldr.takeNodes(Pred);
  580. const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
  581. VisitCXXDeleteExpr(CDE, Pred, Dst);
  582. Bldr.addNodes(Dst);
  583. break;
  584. }
  585. // FIXME: ChooseExpr is really a constant. We need to fix
  586. // the CFG do not model them as explicit control-flow.
  587. case Stmt::ChooseExprClass: { // __builtin_choose_expr
  588. Bldr.takeNodes(Pred);
  589. const ChooseExpr *C = cast<ChooseExpr>(S);
  590. VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
  591. Bldr.addNodes(Dst);
  592. break;
  593. }
  594. case Stmt::CompoundAssignOperatorClass:
  595. Bldr.takeNodes(Pred);
  596. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  597. Bldr.addNodes(Dst);
  598. break;
  599. case Stmt::CompoundLiteralExprClass:
  600. Bldr.takeNodes(Pred);
  601. VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
  602. Bldr.addNodes(Dst);
  603. break;
  604. case Stmt::BinaryConditionalOperatorClass:
  605. case Stmt::ConditionalOperatorClass: { // '?' operator
  606. Bldr.takeNodes(Pred);
  607. const AbstractConditionalOperator *C
  608. = cast<AbstractConditionalOperator>(S);
  609. VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
  610. Bldr.addNodes(Dst);
  611. break;
  612. }
  613. case Stmt::CXXThisExprClass:
  614. Bldr.takeNodes(Pred);
  615. VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
  616. Bldr.addNodes(Dst);
  617. break;
  618. case Stmt::DeclRefExprClass: {
  619. Bldr.takeNodes(Pred);
  620. const DeclRefExpr *DE = cast<DeclRefExpr>(S);
  621. VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
  622. Bldr.addNodes(Dst);
  623. break;
  624. }
  625. case Stmt::DeclStmtClass:
  626. Bldr.takeNodes(Pred);
  627. VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
  628. Bldr.addNodes(Dst);
  629. break;
  630. case Stmt::ImplicitCastExprClass:
  631. case Stmt::CStyleCastExprClass:
  632. case Stmt::CXXStaticCastExprClass:
  633. case Stmt::CXXDynamicCastExprClass:
  634. case Stmt::CXXReinterpretCastExprClass:
  635. case Stmt::CXXConstCastExprClass:
  636. case Stmt::CXXFunctionalCastExprClass:
  637. case Stmt::ObjCBridgedCastExprClass: {
  638. Bldr.takeNodes(Pred);
  639. const CastExpr *C = cast<CastExpr>(S);
  640. // Handle the previsit checks.
  641. ExplodedNodeSet dstPrevisit;
  642. getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this);
  643. // Handle the expression itself.
  644. ExplodedNodeSet dstExpr;
  645. for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
  646. e = dstPrevisit.end(); i != e ; ++i) {
  647. VisitCast(C, C->getSubExpr(), *i, dstExpr);
  648. }
  649. // Handle the postvisit checks.
  650. getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
  651. Bldr.addNodes(Dst);
  652. break;
  653. }
  654. case Expr::MaterializeTemporaryExprClass: {
  655. Bldr.takeNodes(Pred);
  656. const MaterializeTemporaryExpr *Materialize
  657. = cast<MaterializeTemporaryExpr>(S);
  658. if (!Materialize->getType()->isRecordType())
  659. CreateCXXTemporaryObject(Materialize, Pred, Dst);
  660. else
  661. Visit(Materialize->GetTemporaryExpr(), Pred, Dst);
  662. Bldr.addNodes(Dst);
  663. break;
  664. }
  665. case Stmt::InitListExprClass:
  666. Bldr.takeNodes(Pred);
  667. VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
  668. Bldr.addNodes(Dst);
  669. break;
  670. case Stmt::MemberExprClass:
  671. Bldr.takeNodes(Pred);
  672. VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
  673. Bldr.addNodes(Dst);
  674. break;
  675. case Stmt::ObjCIvarRefExprClass:
  676. Bldr.takeNodes(Pred);
  677. VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
  678. Bldr.addNodes(Dst);
  679. break;
  680. case Stmt::ObjCForCollectionStmtClass:
  681. Bldr.takeNodes(Pred);
  682. VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
  683. Bldr.addNodes(Dst);
  684. break;
  685. case Stmt::ObjCMessageExprClass:
  686. Bldr.takeNodes(Pred);
  687. VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
  688. Bldr.addNodes(Dst);
  689. break;
  690. case Stmt::ObjCAtThrowStmtClass: {
  691. // FIXME: This is not complete. We basically treat @throw as
  692. // an abort.
  693. Bldr.generateNode(S, Pred, Pred->getState());
  694. break;
  695. }
  696. case Stmt::ReturnStmtClass:
  697. Bldr.takeNodes(Pred);
  698. VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
  699. Bldr.addNodes(Dst);
  700. break;
  701. case Stmt::OffsetOfExprClass:
  702. Bldr.takeNodes(Pred);
  703. VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
  704. Bldr.addNodes(Dst);
  705. break;
  706. case Stmt::UnaryExprOrTypeTraitExprClass:
  707. Bldr.takeNodes(Pred);
  708. VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
  709. Pred, Dst);
  710. Bldr.addNodes(Dst);
  711. break;
  712. case Stmt::StmtExprClass: {
  713. const StmtExpr *SE = cast<StmtExpr>(S);
  714. if (SE->getSubStmt()->body_empty()) {
  715. // Empty statement expression.
  716. assert(SE->getType() == getContext().VoidTy
  717. && "Empty statement expression must have void type.");
  718. break;
  719. }
  720. if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
  721. ProgramStateRef state = Pred->getState();
  722. Bldr.generateNode(SE, Pred,
  723. state->BindExpr(SE, Pred->getLocationContext(),
  724. state->getSVal(LastExpr,
  725. Pred->getLocationContext())));
  726. }
  727. break;
  728. }
  729. case Stmt::StringLiteralClass: {
  730. ProgramStateRef state = Pred->getState();
  731. SVal V = state->getLValue(cast<StringLiteral>(S));
  732. Bldr.generateNode(S, Pred, state->BindExpr(S, Pred->getLocationContext(),
  733. V));
  734. return;
  735. }
  736. case Stmt::UnaryOperatorClass: {
  737. Bldr.takeNodes(Pred);
  738. const UnaryOperator *U = cast<UnaryOperator>(S);
  739. if (AMgr.shouldEagerlyAssume() && (U->getOpcode() == UO_LNot)) {
  740. ExplodedNodeSet Tmp;
  741. VisitUnaryOperator(U, Pred, Tmp);
  742. evalEagerlyAssume(Dst, Tmp, U);
  743. }
  744. else
  745. VisitUnaryOperator(U, Pred, Dst);
  746. Bldr.addNodes(Dst);
  747. break;
  748. }
  749. case Stmt::PseudoObjectExprClass: {
  750. Bldr.takeNodes(Pred);
  751. ProgramStateRef state = Pred->getState();
  752. const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
  753. if (const Expr *Result = PE->getResultExpr()) {
  754. SVal V = state->getSVal(Result, Pred->getLocationContext());
  755. Bldr.generateNode(S, Pred,
  756. state->BindExpr(S, Pred->getLocationContext(), V));
  757. }
  758. else
  759. Bldr.generateNode(S, Pred,
  760. state->BindExpr(S, Pred->getLocationContext(),
  761. UnknownVal()));
  762. Bldr.addNodes(Dst);
  763. break;
  764. }
  765. }
  766. }
  767. /// Block entrance. (Update counters).
  768. void ExprEngine::processCFGBlockEntrance(NodeBuilderWithSinks &nodeBuilder) {
  769. // FIXME: Refactor this into a checker.
  770. ExplodedNode *pred = nodeBuilder.getContext().getPred();
  771. if (nodeBuilder.getContext().getCurrentBlockCount() >= AMgr.getMaxVisit()) {
  772. static SimpleProgramPointTag tag("ExprEngine : Block count exceeded");
  773. nodeBuilder.generateNode(pred->getState(), pred, &tag, true);
  774. }
  775. }
  776. //===----------------------------------------------------------------------===//
  777. // Branch processing.
  778. //===----------------------------------------------------------------------===//
  779. ProgramStateRef ExprEngine::MarkBranch(ProgramStateRef state,
  780. const Stmt *Terminator,
  781. const LocationContext *LCtx,
  782. bool branchTaken) {
  783. switch (Terminator->getStmtClass()) {
  784. default:
  785. return state;
  786. case Stmt::BinaryOperatorClass: { // '&&' and '||'
  787. const BinaryOperator* B = cast<BinaryOperator>(Terminator);
  788. BinaryOperator::Opcode Op = B->getOpcode();
  789. assert (Op == BO_LAnd || Op == BO_LOr);
  790. // For &&, if we take the true branch, then the value of the whole
  791. // expression is that of the RHS expression.
  792. //
  793. // For ||, if we take the false branch, then the value of the whole
  794. // expression is that of the RHS expression.
  795. const Expr *Ex = (Op == BO_LAnd && branchTaken) ||
  796. (Op == BO_LOr && !branchTaken)
  797. ? B->getRHS() : B->getLHS();
  798. return state->BindExpr(B, LCtx, UndefinedVal(Ex));
  799. }
  800. case Stmt::BinaryConditionalOperatorClass:
  801. case Stmt::ConditionalOperatorClass: { // ?:
  802. const AbstractConditionalOperator* C
  803. = cast<AbstractConditionalOperator>(Terminator);
  804. // For ?, if branchTaken == true then the value is either the LHS or
  805. // the condition itself. (GNU extension).
  806. const Expr *Ex;
  807. if (branchTaken)
  808. Ex = C->getTrueExpr();
  809. else
  810. Ex = C->getFalseExpr();
  811. return state->BindExpr(C, LCtx, UndefinedVal(Ex));
  812. }
  813. case Stmt::ChooseExprClass: { // ?:
  814. const ChooseExpr *C = cast<ChooseExpr>(Terminator);
  815. const Expr *Ex = branchTaken ? C->getLHS() : C->getRHS();
  816. return state->BindExpr(C, LCtx, UndefinedVal(Ex));
  817. }
  818. }
  819. }
  820. /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
  821. /// to try to recover some path-sensitivity for casts of symbolic
  822. /// integers that promote their values (which are currently not tracked well).
  823. /// This function returns the SVal bound to Condition->IgnoreCasts if all the
  824. // cast(s) did was sign-extend the original value.
  825. static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
  826. ProgramStateRef state,
  827. const Stmt *Condition,
  828. const LocationContext *LCtx,
  829. ASTContext &Ctx) {
  830. const Expr *Ex = dyn_cast<Expr>(Condition);
  831. if (!Ex)
  832. return UnknownVal();
  833. uint64_t bits = 0;
  834. bool bitsInit = false;
  835. while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
  836. QualType T = CE->getType();
  837. if (!T->isIntegerType())
  838. return UnknownVal();
  839. uint64_t newBits = Ctx.getTypeSize(T);
  840. if (!bitsInit || newBits < bits) {
  841. bitsInit = true;
  842. bits = newBits;
  843. }
  844. Ex = CE->getSubExpr();
  845. }
  846. // We reached a non-cast. Is it a symbolic value?
  847. QualType T = Ex->getType();
  848. if (!bitsInit || !T->isIntegerType() || Ctx.getTypeSize(T) > bits)
  849. return UnknownVal();
  850. return state->getSVal(Ex, LCtx);
  851. }
  852. void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
  853. NodeBuilderContext& BldCtx,
  854. ExplodedNode *Pred,
  855. ExplodedNodeSet &Dst,
  856. const CFGBlock *DstT,
  857. const CFGBlock *DstF) {
  858. currentBuilderContext = &BldCtx;
  859. // Check for NULL conditions; e.g. "for(;;)"
  860. if (!Condition) {
  861. BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
  862. NullCondBldr.markInfeasible(false);
  863. NullCondBldr.generateNode(Pred->getState(), true, Pred);
  864. return;
  865. }
  866. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  867. Condition->getLocStart(),
  868. "Error evaluating branch");
  869. ExplodedNodeSet CheckersOutSet;
  870. getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
  871. Pred, *this);
  872. // We generated only sinks.
  873. if (CheckersOutSet.empty())
  874. return;
  875. BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
  876. for (NodeBuilder::iterator I = CheckersOutSet.begin(),
  877. E = CheckersOutSet.end(); E != I; ++I) {
  878. ExplodedNode *PredI = *I;
  879. if (PredI->isSink())
  880. continue;
  881. ProgramStateRef PrevState = Pred->getState();
  882. SVal X = PrevState->getSVal(Condition, Pred->getLocationContext());
  883. if (X.isUnknownOrUndef()) {
  884. // Give it a chance to recover from unknown.
  885. if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
  886. if (Ex->getType()->isIntegerType()) {
  887. // Try to recover some path-sensitivity. Right now casts of symbolic
  888. // integers that promote their values are currently not tracked well.
  889. // If 'Condition' is such an expression, try and recover the
  890. // underlying value and use that instead.
  891. SVal recovered = RecoverCastedSymbol(getStateManager(),
  892. PrevState, Condition,
  893. Pred->getLocationContext(),
  894. getContext());
  895. if (!recovered.isUnknown()) {
  896. X = recovered;
  897. }
  898. }
  899. }
  900. }
  901. const LocationContext *LCtx = PredI->getLocationContext();
  902. // If the condition is still unknown, give up.
  903. if (X.isUnknownOrUndef()) {
  904. builder.generateNode(MarkBranch(PrevState, Term, LCtx, true),
  905. true, PredI);
  906. builder.generateNode(MarkBranch(PrevState, Term, LCtx, false),
  907. false, PredI);
  908. continue;
  909. }
  910. DefinedSVal V = cast<DefinedSVal>(X);
  911. // Process the true branch.
  912. if (builder.isFeasible(true)) {
  913. if (ProgramStateRef state = PrevState->assume(V, true))
  914. builder.generateNode(MarkBranch(state, Term, LCtx, true),
  915. true, PredI);
  916. else
  917. builder.markInfeasible(true);
  918. }
  919. // Process the false branch.
  920. if (builder.isFeasible(false)) {
  921. if (ProgramStateRef state = PrevState->assume(V, false))
  922. builder.generateNode(MarkBranch(state, Term, LCtx, false),
  923. false, PredI);
  924. else
  925. builder.markInfeasible(false);
  926. }
  927. }
  928. currentBuilderContext = 0;
  929. }
  930. /// processIndirectGoto - Called by CoreEngine. Used to generate successor
  931. /// nodes by processing the 'effects' of a computed goto jump.
  932. void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
  933. ProgramStateRef state = builder.getState();
  934. SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
  935. // Three possibilities:
  936. //
  937. // (1) We know the computed label.
  938. // (2) The label is NULL (or some other constant), or Undefined.
  939. // (3) We have no clue about the label. Dispatch to all targets.
  940. //
  941. typedef IndirectGotoNodeBuilder::iterator iterator;
  942. if (isa<loc::GotoLabel>(V)) {
  943. const LabelDecl *L = cast<loc::GotoLabel>(V).getLabel();
  944. for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
  945. if (I.getLabel() == L) {
  946. builder.generateNode(I, state);
  947. return;
  948. }
  949. }
  950. llvm_unreachable("No block with label.");
  951. }
  952. if (isa<loc::ConcreteInt>(V) || isa<UndefinedVal>(V)) {
  953. // Dispatch to the first target and mark it as a sink.
  954. //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
  955. // FIXME: add checker visit.
  956. // UndefBranches.insert(N);
  957. return;
  958. }
  959. // This is really a catch-all. We don't support symbolics yet.
  960. // FIXME: Implement dispatch for symbolic pointers.
  961. for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
  962. builder.generateNode(I, state);
  963. }
  964. /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
  965. /// nodes when the control reaches the end of a function.
  966. void ExprEngine::processEndOfFunction(NodeBuilderContext& BC) {
  967. StateMgr.EndPath(BC.Pred->getState());
  968. ExplodedNodeSet Dst;
  969. getCheckerManager().runCheckersForEndPath(BC, Dst, *this);
  970. Engine.enqueueEndOfFunction(Dst);
  971. }
  972. /// ProcessSwitch - Called by CoreEngine. Used to generate successor
  973. /// nodes by processing the 'effects' of a switch statement.
  974. void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
  975. typedef SwitchNodeBuilder::iterator iterator;
  976. ProgramStateRef state = builder.getState();
  977. const Expr *CondE = builder.getCondition();
  978. SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
  979. if (CondV_untested.isUndef()) {
  980. //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
  981. // FIXME: add checker
  982. //UndefBranches.insert(N);
  983. return;
  984. }
  985. DefinedOrUnknownSVal CondV = cast<DefinedOrUnknownSVal>(CondV_untested);
  986. ProgramStateRef DefaultSt = state;
  987. iterator I = builder.begin(), EI = builder.end();
  988. bool defaultIsFeasible = I == EI;
  989. for ( ; I != EI; ++I) {
  990. // Successor may be pruned out during CFG construction.
  991. if (!I.getBlock())
  992. continue;
  993. const CaseStmt *Case = I.getCase();
  994. // Evaluate the LHS of the case value.
  995. llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
  996. assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType()));
  997. // Get the RHS of the case, if it exists.
  998. llvm::APSInt V2;
  999. if (const Expr *E = Case->getRHS())
  1000. V2 = E->EvaluateKnownConstInt(getContext());
  1001. else
  1002. V2 = V1;
  1003. // FIXME: Eventually we should replace the logic below with a range
  1004. // comparison, rather than concretize the values within the range.
  1005. // This should be easy once we have "ranges" for NonLVals.
  1006. do {
  1007. nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1));
  1008. DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state,
  1009. CondV, CaseVal);
  1010. // Now "assume" that the case matches.
  1011. if (ProgramStateRef stateNew = state->assume(Res, true)) {
  1012. builder.generateCaseStmtNode(I, stateNew);
  1013. // If CondV evaluates to a constant, then we know that this
  1014. // is the *only* case that we can take, so stop evaluating the
  1015. // others.
  1016. if (isa<nonloc::ConcreteInt>(CondV))
  1017. return;
  1018. }
  1019. // Now "assume" that the case doesn't match. Add this state
  1020. // to the default state (if it is feasible).
  1021. if (DefaultSt) {
  1022. if (ProgramStateRef stateNew = DefaultSt->assume(Res, false)) {
  1023. defaultIsFeasible = true;
  1024. DefaultSt = stateNew;
  1025. }
  1026. else {
  1027. defaultIsFeasible = false;
  1028. DefaultSt = NULL;
  1029. }
  1030. }
  1031. // Concretize the next value in the range.
  1032. if (V1 == V2)
  1033. break;
  1034. ++V1;
  1035. assert (V1 <= V2);
  1036. } while (true);
  1037. }
  1038. if (!defaultIsFeasible)
  1039. return;
  1040. // If we have switch(enum value), the default branch is not
  1041. // feasible if all of the enum constants not covered by 'case:' statements
  1042. // are not feasible values for the switch condition.
  1043. //
  1044. // Note that this isn't as accurate as it could be. Even if there isn't
  1045. // a case for a particular enum value as long as that enum value isn't
  1046. // feasible then it shouldn't be considered for making 'default:' reachable.
  1047. const SwitchStmt *SS = builder.getSwitch();
  1048. const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
  1049. if (CondExpr->getType()->getAs<EnumType>()) {
  1050. if (SS->isAllEnumCasesCovered())
  1051. return;
  1052. }
  1053. builder.generateDefaultCaseNode(DefaultSt);
  1054. }
  1055. //===----------------------------------------------------------------------===//
  1056. // Transfer functions: Loads and stores.
  1057. //===----------------------------------------------------------------------===//
  1058. void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
  1059. ExplodedNode *Pred,
  1060. ExplodedNodeSet &Dst) {
  1061. StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
  1062. ProgramStateRef state = Pred->getState();
  1063. const LocationContext *LCtx = Pred->getLocationContext();
  1064. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1065. assert(Ex->isLValue());
  1066. SVal V = state->getLValue(VD, Pred->getLocationContext());
  1067. // For references, the 'lvalue' is the pointer address stored in the
  1068. // reference region.
  1069. if (VD->getType()->isReferenceType()) {
  1070. if (const MemRegion *R = V.getAsRegion())
  1071. V = state->getSVal(R);
  1072. else
  1073. V = UnknownVal();
  1074. }
  1075. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), false, 0,
  1076. ProgramPoint::PostLValueKind);
  1077. return;
  1078. }
  1079. if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
  1080. assert(!Ex->isLValue());
  1081. SVal V = svalBuilder.makeIntVal(ED->getInitVal());
  1082. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
  1083. return;
  1084. }
  1085. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1086. SVal V = svalBuilder.getFunctionPointer(FD);
  1087. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), false, 0,
  1088. ProgramPoint::PostLValueKind);
  1089. return;
  1090. }
  1091. assert (false &&
  1092. "ValueDecl support for this ValueDecl not implemented.");
  1093. }
  1094. /// VisitArraySubscriptExpr - Transfer function for array accesses
  1095. void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A,
  1096. ExplodedNode *Pred,
  1097. ExplodedNodeSet &Dst){
  1098. const Expr *Base = A->getBase()->IgnoreParens();
  1099. const Expr *Idx = A->getIdx()->IgnoreParens();
  1100. ExplodedNodeSet checkerPreStmt;
  1101. getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this);
  1102. StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currentBuilderContext);
  1103. for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(),
  1104. ei = checkerPreStmt.end(); it != ei; ++it) {
  1105. const LocationContext *LCtx = (*it)->getLocationContext();
  1106. ProgramStateRef state = (*it)->getState();
  1107. SVal V = state->getLValue(A->getType(),
  1108. state->getSVal(Idx, LCtx),
  1109. state->getSVal(Base, LCtx));
  1110. assert(A->isLValue());
  1111. Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V),
  1112. false, 0, ProgramPoint::PostLValueKind);
  1113. }
  1114. }
  1115. /// VisitMemberExpr - Transfer function for member expressions.
  1116. void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
  1117. ExplodedNodeSet &TopDst) {
  1118. StmtNodeBuilder Bldr(Pred, TopDst, *currentBuilderContext);
  1119. ExplodedNodeSet Dst;
  1120. Decl *member = M->getMemberDecl();
  1121. if (VarDecl *VD = dyn_cast<VarDecl>(member)) {
  1122. assert(M->isLValue());
  1123. Bldr.takeNodes(Pred);
  1124. VisitCommonDeclRefExpr(M, VD, Pred, Dst);
  1125. Bldr.addNodes(Dst);
  1126. return;
  1127. }
  1128. FieldDecl *field = dyn_cast<FieldDecl>(member);
  1129. if (!field) // FIXME: skipping member expressions for non-fields
  1130. return;
  1131. Expr *baseExpr = M->getBase()->IgnoreParens();
  1132. ProgramStateRef state = Pred->getState();
  1133. const LocationContext *LCtx = Pred->getLocationContext();
  1134. SVal baseExprVal = state->getSVal(baseExpr, Pred->getLocationContext());
  1135. if (isa<nonloc::LazyCompoundVal>(baseExprVal) ||
  1136. isa<nonloc::CompoundVal>(baseExprVal) ||
  1137. // FIXME: This can originate by conjuring a symbol for an unknown
  1138. // temporary struct object, see test/Analysis/fields.c:
  1139. // (p = getit()).x
  1140. isa<nonloc::SymbolVal>(baseExprVal)) {
  1141. Bldr.generateNode(M, Pred, state->BindExpr(M, LCtx, UnknownVal()));
  1142. return;
  1143. }
  1144. // FIXME: Should we insert some assumption logic in here to determine
  1145. // if "Base" is a valid piece of memory? Before we put this assumption
  1146. // later when using FieldOffset lvals (which we no longer have).
  1147. // For all other cases, compute an lvalue.
  1148. SVal L = state->getLValue(field, baseExprVal);
  1149. if (M->isLValue())
  1150. Bldr.generateNode(M, Pred, state->BindExpr(M, LCtx, L), false, 0,
  1151. ProgramPoint::PostLValueKind);
  1152. else {
  1153. Bldr.takeNodes(Pred);
  1154. evalLoad(Dst, M, Pred, state, L);
  1155. Bldr.addNodes(Dst);
  1156. }
  1157. }
  1158. /// evalBind - Handle the semantics of binding a value to a specific location.
  1159. /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
  1160. void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
  1161. ExplodedNode *Pred,
  1162. SVal location, SVal Val, bool atDeclInit,
  1163. ProgramPoint::Kind PointKind) {
  1164. // Do a previsit of the bind.
  1165. ExplodedNodeSet CheckedSet;
  1166. getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
  1167. StoreE, *this, PointKind);
  1168. // TODO:AZ Remove TmpDst after NB refactoring is done.
  1169. ExplodedNodeSet TmpDst;
  1170. StmtNodeBuilder Bldr(CheckedSet, TmpDst, *currentBuilderContext);
  1171. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  1172. I!=E; ++I) {
  1173. ProgramStateRef state = (*I)->getState();
  1174. if (atDeclInit) {
  1175. const VarRegion *VR =
  1176. cast<VarRegion>(cast<loc::MemRegionVal>(location).getRegion());
  1177. state = state->bindDecl(VR, Val);
  1178. } else {
  1179. state = state->bindLoc(location, Val);
  1180. }
  1181. Bldr.generateNode(StoreE, *I, state, false, 0, PointKind);
  1182. }
  1183. Dst.insert(TmpDst);
  1184. }
  1185. /// evalStore - Handle the semantics of a store via an assignment.
  1186. /// @param Dst The node set to store generated state nodes
  1187. /// @param AssignE The assignment expression if the store happens in an
  1188. /// assignment.
  1189. /// @param LocatioinE The location expression that is stored to.
  1190. /// @param state The current simulation state
  1191. /// @param location The location to store the value
  1192. /// @param Val The value to be stored
  1193. void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
  1194. const Expr *LocationE,
  1195. ExplodedNode *Pred,
  1196. ProgramStateRef state, SVal location, SVal Val,
  1197. const ProgramPointTag *tag) {
  1198. // Proceed with the store. We use AssignE as the anchor for the PostStore
  1199. // ProgramPoint if it is non-NULL, and LocationE otherwise.
  1200. const Expr *StoreE = AssignE ? AssignE : LocationE;
  1201. if (isa<loc::ObjCPropRef>(location)) {
  1202. loc::ObjCPropRef prop = cast<loc::ObjCPropRef>(location);
  1203. return VisitObjCMessage(ObjCPropertySetter(prop.getPropRefExpr(),
  1204. StoreE, Val), Pred, Dst);
  1205. }
  1206. // Evaluate the location (checks for bad dereferences).
  1207. ExplodedNodeSet Tmp;
  1208. evalLocation(Tmp, LocationE, Pred, state, location, tag, false);
  1209. if (Tmp.empty())
  1210. return;
  1211. if (location.isUndef())
  1212. return;
  1213. for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
  1214. evalBind(Dst, StoreE, *NI, location, Val, false,
  1215. ProgramPoint::PostStoreKind);
  1216. }
  1217. void ExprEngine::evalLoad(ExplodedNodeSet &Dst, const Expr *Ex,
  1218. ExplodedNode *Pred,
  1219. ProgramStateRef state, SVal location,
  1220. const ProgramPointTag *tag, QualType LoadTy) {
  1221. assert(!isa<NonLoc>(location) && "location cannot be a NonLoc.");
  1222. if (isa<loc::ObjCPropRef>(location)) {
  1223. loc::ObjCPropRef prop = cast<loc::ObjCPropRef>(location);
  1224. return VisitObjCMessage(ObjCPropertyGetter(prop.getPropRefExpr(), Ex),
  1225. Pred, Dst);
  1226. }
  1227. // Are we loading from a region? This actually results in two loads; one
  1228. // to fetch the address of the referenced value and one to fetch the
  1229. // referenced value.
  1230. if (const TypedValueRegion *TR =
  1231. dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
  1232. QualType ValTy = TR->getValueType();
  1233. if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
  1234. static SimpleProgramPointTag
  1235. loadReferenceTag("ExprEngine : Load Reference");
  1236. ExplodedNodeSet Tmp;
  1237. evalLoadCommon(Tmp, Ex, Pred, state, location, &loadReferenceTag,
  1238. getContext().getPointerType(RT->getPointeeType()));
  1239. // Perform the load from the referenced value.
  1240. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
  1241. state = (*I)->getState();
  1242. location = state->getSVal(Ex, (*I)->getLocationContext());
  1243. evalLoadCommon(Dst, Ex, *I, state, location, tag, LoadTy);
  1244. }
  1245. return;
  1246. }
  1247. }
  1248. evalLoadCommon(Dst, Ex, Pred, state, location, tag, LoadTy);
  1249. }
  1250. void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst, const Expr *Ex,
  1251. ExplodedNode *Pred,
  1252. ProgramStateRef state, SVal location,
  1253. const ProgramPointTag *tag, QualType LoadTy) {
  1254. // Evaluate the location (checks for bad dereferences).
  1255. ExplodedNodeSet Tmp;
  1256. evalLocation(Tmp, Ex, Pred, state, location, tag, true);
  1257. if (Tmp.empty())
  1258. return;
  1259. StmtNodeBuilder Bldr(Tmp, Dst, *currentBuilderContext);
  1260. if (location.isUndef())
  1261. return;
  1262. // Proceed with the load.
  1263. for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
  1264. state = (*NI)->getState();
  1265. const LocationContext *LCtx = (*NI)->getLocationContext();
  1266. if (location.isUnknown()) {
  1267. // This is important. We must nuke the old binding.
  1268. Bldr.generateNode(Ex, *NI, state->BindExpr(Ex, LCtx, UnknownVal()),
  1269. false, tag, ProgramPoint::PostLoadKind);
  1270. }
  1271. else {
  1272. if (LoadTy.isNull())
  1273. LoadTy = Ex->getType();
  1274. SVal V = state->getSVal(cast<Loc>(location), LoadTy);
  1275. Bldr.generateNode(Ex, *NI, state->bindExprAndLocation(Ex, LCtx,
  1276. location, V),
  1277. false, tag, ProgramPoint::PostLoadKind);
  1278. }
  1279. }
  1280. }
  1281. void ExprEngine::evalLocation(ExplodedNodeSet &Dst, const Stmt *S,
  1282. ExplodedNode *Pred,
  1283. ProgramStateRef state, SVal location,
  1284. const ProgramPointTag *tag, bool isLoad) {
  1285. StmtNodeBuilder BldrTop(Pred, Dst, *currentBuilderContext);
  1286. // Early checks for performance reason.
  1287. if (location.isUnknown()) {
  1288. return;
  1289. }
  1290. ExplodedNodeSet Src;
  1291. BldrTop.takeNodes(Pred);
  1292. StmtNodeBuilder Bldr(Pred, Src, *currentBuilderContext);
  1293. if (Pred->getState() != state) {
  1294. // Associate this new state with an ExplodedNode.
  1295. // FIXME: If I pass null tag, the graph is incorrect, e.g for
  1296. // int *p;
  1297. // p = 0;
  1298. // *p = 0xDEADBEEF;
  1299. // "p = 0" is not noted as "Null pointer value stored to 'p'" but
  1300. // instead "int *p" is noted as
  1301. // "Variable 'p' initialized to a null pointer value"
  1302. // FIXME: why is 'tag' not used instead of etag?
  1303. static SimpleProgramPointTag etag("ExprEngine: Location");
  1304. Bldr.generateNode(S, Pred, state, false, &etag);
  1305. }
  1306. ExplodedNodeSet Tmp;
  1307. getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad, S,
  1308. *this);
  1309. BldrTop.addNodes(Tmp);
  1310. }
  1311. std::pair<const ProgramPointTag *, const ProgramPointTag*>
  1312. ExprEngine::getEagerlyAssumeTags() {
  1313. static SimpleProgramPointTag
  1314. EagerlyAssumeTrue("ExprEngine : Eagerly Assume True"),
  1315. EagerlyAssumeFalse("ExprEngine : Eagerly Assume False");
  1316. return std::make_pair(&EagerlyAssumeTrue, &EagerlyAssumeFalse);
  1317. }
  1318. void ExprEngine::evalEagerlyAssume(ExplodedNodeSet &Dst, ExplodedNodeSet &Src,
  1319. const Expr *Ex) {
  1320. StmtNodeBuilder Bldr(Src, Dst, *currentBuilderContext);
  1321. for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
  1322. ExplodedNode *Pred = *I;
  1323. // Test if the previous node was as the same expression. This can happen
  1324. // when the expression fails to evaluate to anything meaningful and
  1325. // (as an optimization) we don't generate a node.
  1326. ProgramPoint P = Pred->getLocation();
  1327. if (!isa<PostStmt>(P) || cast<PostStmt>(P).getStmt() != Ex) {
  1328. continue;
  1329. }
  1330. ProgramStateRef state = Pred->getState();
  1331. SVal V = state->getSVal(Ex, Pred->getLocationContext());
  1332. nonloc::SymbolVal *SEV = dyn_cast<nonloc::SymbolVal>(&V);
  1333. if (SEV && SEV->isExpression()) {
  1334. const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
  1335. getEagerlyAssumeTags();
  1336. // First assume that the condition is true.
  1337. if (ProgramStateRef StateTrue = state->assume(*SEV, true)) {
  1338. SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
  1339. StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
  1340. Bldr.generateNode(Ex, Pred, StateTrue, false, tags.first);
  1341. }
  1342. // Next, assume that the condition is false.
  1343. if (ProgramStateRef StateFalse = state->assume(*SEV, false)) {
  1344. SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
  1345. StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
  1346. Bldr.generateNode(Ex, Pred, StateFalse, false, tags.second);
  1347. }
  1348. }
  1349. }
  1350. }
  1351. void ExprEngine::VisitAsmStmt(const AsmStmt *A, ExplodedNode *Pred,
  1352. ExplodedNodeSet &Dst) {
  1353. VisitAsmStmtHelperOutputs(A, A->begin_outputs(), A->end_outputs(), Pred, Dst);
  1354. }
  1355. void ExprEngine::VisitAsmStmtHelperOutputs(const AsmStmt *A,
  1356. AsmStmt::const_outputs_iterator I,
  1357. AsmStmt::const_outputs_iterator E,
  1358. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  1359. if (I == E) {
  1360. VisitAsmStmtHelperInputs(A, A->begin_inputs(), A->end_inputs(), Pred, Dst);
  1361. return;
  1362. }
  1363. ExplodedNodeSet Tmp;
  1364. Visit(*I, Pred, Tmp);
  1365. ++I;
  1366. for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end();NI != NE;++NI)
  1367. VisitAsmStmtHelperOutputs(A, I, E, *NI, Dst);
  1368. }
  1369. void ExprEngine::VisitAsmStmtHelperInputs(const AsmStmt *A,
  1370. AsmStmt::const_inputs_iterator I,
  1371. AsmStmt::const_inputs_iterator E,
  1372. ExplodedNode *Pred,
  1373. ExplodedNodeSet &Dst) {
  1374. if (I == E) {
  1375. StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
  1376. // We have processed both the inputs and the outputs. All of the outputs
  1377. // should evaluate to Locs. Nuke all of their values.
  1378. // FIXME: Some day in the future it would be nice to allow a "plug-in"
  1379. // which interprets the inline asm and stores proper results in the
  1380. // outputs.
  1381. ProgramStateRef state = Pred->getState();
  1382. for (AsmStmt::const_outputs_iterator OI = A->begin_outputs(),
  1383. OE = A->end_outputs(); OI != OE; ++OI) {
  1384. SVal X = state->getSVal(*OI, Pred->getLocationContext());
  1385. assert (!isa<NonLoc>(X)); // Should be an Lval, or unknown, undef.
  1386. if (isa<Loc>(X))
  1387. state = state->bindLoc(cast<Loc>(X), UnknownVal());
  1388. }
  1389. Bldr.generateNode(A, Pred, state);
  1390. return;
  1391. }
  1392. ExplodedNodeSet Tmp;
  1393. Visit(*I, Pred, Tmp);
  1394. ++I;
  1395. for (ExplodedNodeSet::iterator NI = Tmp.begin(), NE = Tmp.end(); NI!=NE; ++NI)
  1396. VisitAsmStmtHelperInputs(A, I, E, *NI, Dst);
  1397. }
  1398. //===----------------------------------------------------------------------===//
  1399. // Visualization.
  1400. //===----------------------------------------------------------------------===//
  1401. #ifndef NDEBUG
  1402. static ExprEngine* GraphPrintCheckerState;
  1403. static SourceManager* GraphPrintSourceManager;
  1404. namespace llvm {
  1405. template<>
  1406. struct DOTGraphTraits<ExplodedNode*> :
  1407. public DefaultDOTGraphTraits {
  1408. DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
  1409. // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
  1410. // work.
  1411. static std::string getNodeAttributes(const ExplodedNode *N, void*) {
  1412. #if 0
  1413. // FIXME: Replace with a general scheme to tell if the node is
  1414. // an error node.
  1415. if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
  1416. GraphPrintCheckerState->isExplicitNullDeref(N) ||
  1417. GraphPrintCheckerState->isUndefDeref(N) ||
  1418. GraphPrintCheckerState->isUndefStore(N) ||
  1419. GraphPrintCheckerState->isUndefControlFlow(N) ||
  1420. GraphPrintCheckerState->isUndefResult(N) ||
  1421. GraphPrintCheckerState->isBadCall(N) ||
  1422. GraphPrintCheckerState->isUndefArg(N))
  1423. return "color=\"red\",style=\"filled\"";
  1424. if (GraphPrintCheckerState->isNoReturnCall(N))
  1425. return "color=\"blue\",style=\"filled\"";
  1426. #endif
  1427. return "";
  1428. }
  1429. static std::string getNodeLabel(const ExplodedNode *N, void*){
  1430. std::string sbuf;
  1431. llvm::raw_string_ostream Out(sbuf);
  1432. // Program Location.
  1433. ProgramPoint Loc = N->getLocation();
  1434. switch (Loc.getKind()) {
  1435. case ProgramPoint::BlockEntranceKind:
  1436. Out << "Block Entrance: B"
  1437. << cast<BlockEntrance>(Loc).getBlock()->getBlockID();
  1438. break;
  1439. case ProgramPoint::BlockExitKind:
  1440. assert (false);
  1441. break;
  1442. case ProgramPoint::CallEnterKind:
  1443. Out << "CallEnter";
  1444. break;
  1445. case ProgramPoint::CallExitKind:
  1446. Out << "CallExit";
  1447. break;
  1448. default: {
  1449. if (StmtPoint *L = dyn_cast<StmtPoint>(&Loc)) {
  1450. const Stmt *S = L->getStmt();
  1451. SourceLocation SLoc = S->getLocStart();
  1452. Out << S->getStmtClassName() << ' ' << (void*) S << ' ';
  1453. LangOptions LO; // FIXME.
  1454. S->printPretty(Out, 0, PrintingPolicy(LO));
  1455. if (SLoc.isFileID()) {
  1456. Out << "\\lline="
  1457. << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
  1458. << " col="
  1459. << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
  1460. << "\\l";
  1461. }
  1462. if (isa<PreStmt>(Loc))
  1463. Out << "\\lPreStmt\\l;";
  1464. else if (isa<PostLoad>(Loc))
  1465. Out << "\\lPostLoad\\l;";
  1466. else if (isa<PostStore>(Loc))
  1467. Out << "\\lPostStore\\l";
  1468. else if (isa<PostLValue>(Loc))
  1469. Out << "\\lPostLValue\\l";
  1470. #if 0
  1471. // FIXME: Replace with a general scheme to determine
  1472. // the name of the check.
  1473. if (GraphPrintCheckerState->isImplicitNullDeref(N))
  1474. Out << "\\|Implicit-Null Dereference.\\l";
  1475. else if (GraphPrintCheckerState->isExplicitNullDeref(N))
  1476. Out << "\\|Explicit-Null Dereference.\\l";
  1477. else if (GraphPrintCheckerState->isUndefDeref(N))
  1478. Out << "\\|Dereference of undefialied value.\\l";
  1479. else if (GraphPrintCheckerState->isUndefStore(N))
  1480. Out << "\\|Store to Undefined Loc.";
  1481. else if (GraphPrintCheckerState->isUndefResult(N))
  1482. Out << "\\|Result of operation is undefined.";
  1483. else if (GraphPrintCheckerState->isNoReturnCall(N))
  1484. Out << "\\|Call to function marked \"noreturn\".";
  1485. else if (GraphPrintCheckerState->isBadCall(N))
  1486. Out << "\\|Call to NULL/Undefined.";
  1487. else if (GraphPrintCheckerState->isUndefArg(N))
  1488. Out << "\\|Argument in call is undefined";
  1489. #endif
  1490. break;
  1491. }
  1492. const BlockEdge &E = cast<BlockEdge>(Loc);
  1493. Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
  1494. << E.getDst()->getBlockID() << ')';
  1495. if (const Stmt *T = E.getSrc()->getTerminator()) {
  1496. SourceLocation SLoc = T->getLocStart();
  1497. Out << "\\|Terminator: ";
  1498. LangOptions LO; // FIXME.
  1499. E.getSrc()->printTerminator(Out, LO);
  1500. if (SLoc.isFileID()) {
  1501. Out << "\\lline="
  1502. << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
  1503. << " col="
  1504. << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
  1505. }
  1506. if (isa<SwitchStmt>(T)) {
  1507. const Stmt *Label = E.getDst()->getLabel();
  1508. if (Label) {
  1509. if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
  1510. Out << "\\lcase ";
  1511. LangOptions LO; // FIXME.
  1512. C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO));
  1513. if (const Stmt *RHS = C->getRHS()) {
  1514. Out << " .. ";
  1515. RHS->printPretty(Out, 0, PrintingPolicy(LO));
  1516. }
  1517. Out << ":";
  1518. }
  1519. else {
  1520. assert (isa<DefaultStmt>(Label));
  1521. Out << "\\ldefault:";
  1522. }
  1523. }
  1524. else
  1525. Out << "\\l(implicit) default:";
  1526. }
  1527. else if (isa<IndirectGotoStmt>(T)) {
  1528. // FIXME
  1529. }
  1530. else {
  1531. Out << "\\lCondition: ";
  1532. if (*E.getSrc()->succ_begin() == E.getDst())
  1533. Out << "true";
  1534. else
  1535. Out << "false";
  1536. }
  1537. Out << "\\l";
  1538. }
  1539. #if 0
  1540. // FIXME: Replace with a general scheme to determine
  1541. // the name of the check.
  1542. if (GraphPrintCheckerState->isUndefControlFlow(N)) {
  1543. Out << "\\|Control-flow based on\\lUndefined value.\\l";
  1544. }
  1545. #endif
  1546. }
  1547. }
  1548. ProgramStateRef state = N->getState();
  1549. Out << "\\|StateID: " << (void*) state.getPtr()
  1550. << " NodeID: " << (void*) N << "\\|";
  1551. state->printDOT(Out);
  1552. Out << "\\l";
  1553. if (const ProgramPointTag *tag = Loc.getTag()) {
  1554. Out << "\\|Tag: " << tag->getTagDescription();
  1555. Out << "\\l";
  1556. }
  1557. return Out.str();
  1558. }
  1559. };
  1560. } // end llvm namespace
  1561. #endif
  1562. #ifndef NDEBUG
  1563. template <typename ITERATOR>
  1564. ExplodedNode *GetGraphNode(ITERATOR I) { return *I; }
  1565. template <> ExplodedNode*
  1566. GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator>
  1567. (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) {
  1568. return I->first;
  1569. }
  1570. #endif
  1571. void ExprEngine::ViewGraph(bool trim) {
  1572. #ifndef NDEBUG
  1573. if (trim) {
  1574. std::vector<ExplodedNode*> Src;
  1575. // Flush any outstanding reports to make sure we cover all the nodes.
  1576. // This does not cause them to get displayed.
  1577. for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
  1578. const_cast<BugType*>(*I)->FlushReports(BR);
  1579. // Iterate through the reports and get their nodes.
  1580. for (BugReporter::EQClasses_iterator
  1581. EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
  1582. BugReportEquivClass& EQ = *EI;
  1583. const BugReport &R = **EQ.begin();
  1584. ExplodedNode *N = const_cast<ExplodedNode*>(R.getErrorNode());
  1585. if (N) Src.push_back(N);
  1586. }
  1587. ViewGraph(&Src[0], &Src[0]+Src.size());
  1588. }
  1589. else {
  1590. GraphPrintCheckerState = this;
  1591. GraphPrintSourceManager = &getContext().getSourceManager();
  1592. llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
  1593. GraphPrintCheckerState = NULL;
  1594. GraphPrintSourceManager = NULL;
  1595. }
  1596. #endif
  1597. }
  1598. void ExprEngine::ViewGraph(ExplodedNode** Beg, ExplodedNode** End) {
  1599. #ifndef NDEBUG
  1600. GraphPrintCheckerState = this;
  1601. GraphPrintSourceManager = &getContext().getSourceManager();
  1602. std::auto_ptr<ExplodedGraph> TrimmedG(G.Trim(Beg, End).first);
  1603. if (!TrimmedG.get())
  1604. llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
  1605. else
  1606. llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
  1607. GraphPrintCheckerState = NULL;
  1608. GraphPrintSourceManager = NULL;
  1609. #endif
  1610. }