ExprEngine.cpp 64 KB

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