ExprEngine.cpp 68 KB

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