ExprEngine.cpp 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313
  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. #define DEBUG_TYPE "ExprEngine"
  16. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/ParentMap.h"
  19. #include "clang/AST/StmtCXX.h"
  20. #include "clang/AST/StmtObjC.h"
  21. #include "clang/Basic/Builtins.h"
  22. #include "clang/Basic/PrettyStackTrace.h"
  23. #include "clang/Basic/SourceManager.h"
  24. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  25. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  26. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  27. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  28. #include "llvm/ADT/ImmutableList.h"
  29. #include "llvm/ADT/Statistic.h"
  30. #include "llvm/Support/raw_ostream.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. STATISTIC(NumRemoveDeadBindings,
  38. "The # of times RemoveDeadBindings is called");
  39. STATISTIC(NumMaxBlockCountReached,
  40. "The # of aborted paths due to reaching the maximum block count in "
  41. "a top level function");
  42. STATISTIC(NumMaxBlockCountReachedInInlined,
  43. "The # of aborted paths due to reaching the maximum block count in "
  44. "an inlined function");
  45. STATISTIC(NumTimesRetriedWithoutInlining,
  46. "The # of times we re-evaluated a call without inlining");
  47. //===----------------------------------------------------------------------===//
  48. // Engine construction and deletion.
  49. //===----------------------------------------------------------------------===//
  50. ExprEngine::ExprEngine(AnalysisManager &mgr, bool gcEnabled,
  51. SetOfConstDecls *VisitedCalleesIn,
  52. FunctionSummariesTy *FS,
  53. InliningModes HowToInlineIn)
  54. : AMgr(mgr),
  55. AnalysisDeclContexts(mgr.getAnalysisDeclContextManager()),
  56. Engine(*this, FS),
  57. G(Engine.getGraph()),
  58. StateMgr(getContext(), mgr.getStoreManagerCreator(),
  59. mgr.getConstraintManagerCreator(), G.getAllocator(),
  60. this),
  61. SymMgr(StateMgr.getSymbolManager()),
  62. svalBuilder(StateMgr.getSValBuilder()),
  63. currStmtIdx(0), currBldrCtx(0),
  64. ObjCNoRet(mgr.getASTContext()),
  65. ObjCGCEnabled(gcEnabled), BR(mgr, *this),
  66. VisitedCallees(VisitedCalleesIn),
  67. HowToInline(HowToInlineIn)
  68. {
  69. unsigned TrimInterval = mgr.options.getGraphTrimInterval();
  70. if (TrimInterval != 0) {
  71. // Enable eager node reclaimation when constructing the ExplodedGraph.
  72. G.enableNodeReclamation(TrimInterval);
  73. }
  74. }
  75. ExprEngine::~ExprEngine() {
  76. BR.FlushReports();
  77. }
  78. //===----------------------------------------------------------------------===//
  79. // Utility methods.
  80. //===----------------------------------------------------------------------===//
  81. ProgramStateRef ExprEngine::getInitialState(const LocationContext *InitLoc) {
  82. ProgramStateRef state = StateMgr.getInitialState(InitLoc);
  83. const Decl *D = InitLoc->getDecl();
  84. // Preconditions.
  85. // FIXME: It would be nice if we had a more general mechanism to add
  86. // such preconditions. Some day.
  87. do {
  88. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  89. // Precondition: the first argument of 'main' is an integer guaranteed
  90. // to be > 0.
  91. const IdentifierInfo *II = FD->getIdentifier();
  92. if (!II || !(II->getName() == "main" && FD->getNumParams() > 0))
  93. break;
  94. const ParmVarDecl *PD = FD->getParamDecl(0);
  95. QualType T = PD->getType();
  96. if (!T->isIntegerType())
  97. break;
  98. const MemRegion *R = state->getRegion(PD, InitLoc);
  99. if (!R)
  100. break;
  101. SVal V = state->getSVal(loc::MemRegionVal(R));
  102. SVal Constraint_untested = evalBinOp(state, BO_GT, V,
  103. svalBuilder.makeZeroVal(T),
  104. getContext().IntTy);
  105. DefinedOrUnknownSVal *Constraint =
  106. dyn_cast<DefinedOrUnknownSVal>(&Constraint_untested);
  107. if (!Constraint)
  108. break;
  109. if (ProgramStateRef newState = state->assume(*Constraint, true))
  110. state = newState;
  111. }
  112. break;
  113. }
  114. while (0);
  115. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  116. // Precondition: 'self' is always non-null upon entry to an Objective-C
  117. // method.
  118. const ImplicitParamDecl *SelfD = MD->getSelfDecl();
  119. const MemRegion *R = state->getRegion(SelfD, InitLoc);
  120. SVal V = state->getSVal(loc::MemRegionVal(R));
  121. if (const Loc *LV = dyn_cast<Loc>(&V)) {
  122. // Assume that the pointer value in 'self' is non-null.
  123. state = state->assume(*LV, true);
  124. assert(state && "'self' cannot be null");
  125. }
  126. }
  127. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  128. if (!MD->isStatic()) {
  129. // Precondition: 'this' is always non-null upon entry to the
  130. // top-level function. This is our starting assumption for
  131. // analyzing an "open" program.
  132. const StackFrameContext *SFC = InitLoc->getCurrentStackFrame();
  133. if (SFC->getParent() == 0) {
  134. loc::MemRegionVal L = svalBuilder.getCXXThis(MD, SFC);
  135. SVal V = state->getSVal(L);
  136. if (const Loc *LV = dyn_cast<Loc>(&V)) {
  137. state = state->assume(*LV, true);
  138. assert(state && "'this' cannot be null");
  139. }
  140. }
  141. }
  142. }
  143. return state;
  144. }
  145. /// If the value of the given expression is a NonLoc, copy it into a new
  146. /// temporary region, and replace the value of the expression with that.
  147. static ProgramStateRef createTemporaryRegionIfNeeded(ProgramStateRef State,
  148. const LocationContext *LC,
  149. const Expr *E) {
  150. SVal V = State->getSVal(E, LC);
  151. if (isa<NonLoc>(V)) {
  152. MemRegionManager &MRMgr = State->getStateManager().getRegionManager();
  153. const MemRegion *R = MRMgr.getCXXTempObjectRegion(E, LC);
  154. State = State->bindLoc(loc::MemRegionVal(R), V);
  155. State = State->BindExpr(E, LC, loc::MemRegionVal(R));
  156. }
  157. return State;
  158. }
  159. //===----------------------------------------------------------------------===//
  160. // Top-level transfer function logic (Dispatcher).
  161. //===----------------------------------------------------------------------===//
  162. /// evalAssume - Called by ConstraintManager. Used to call checker-specific
  163. /// logic for handling assumptions on symbolic values.
  164. ProgramStateRef ExprEngine::processAssume(ProgramStateRef state,
  165. SVal cond, bool assumption) {
  166. return getCheckerManager().runCheckersForEvalAssume(state, cond, assumption);
  167. }
  168. bool ExprEngine::wantsRegionChangeUpdate(ProgramStateRef state) {
  169. return getCheckerManager().wantsRegionChangeUpdate(state);
  170. }
  171. ProgramStateRef
  172. ExprEngine::processRegionChanges(ProgramStateRef state,
  173. const InvalidatedSymbols *invalidated,
  174. ArrayRef<const MemRegion *> Explicits,
  175. ArrayRef<const MemRegion *> Regions,
  176. const CallEvent *Call) {
  177. return getCheckerManager().runCheckersForRegionChanges(state, invalidated,
  178. Explicits, Regions, Call);
  179. }
  180. void ExprEngine::printState(raw_ostream &Out, ProgramStateRef State,
  181. const char *NL, const char *Sep) {
  182. getCheckerManager().runCheckersForPrintState(Out, State, NL, Sep);
  183. }
  184. void ExprEngine::processEndWorklist(bool hasWorkRemaining) {
  185. getCheckerManager().runCheckersForEndAnalysis(G, BR, *this);
  186. }
  187. void ExprEngine::processCFGElement(const CFGElement E, ExplodedNode *Pred,
  188. unsigned StmtIdx, NodeBuilderContext *Ctx) {
  189. currStmtIdx = StmtIdx;
  190. currBldrCtx = Ctx;
  191. switch (E.getKind()) {
  192. case CFGElement::Invalid:
  193. llvm_unreachable("Unexpected CFGElement kind.");
  194. case CFGElement::Statement:
  195. ProcessStmt(const_cast<Stmt*>(E.getAs<CFGStmt>()->getStmt()), Pred);
  196. return;
  197. case CFGElement::Initializer:
  198. ProcessInitializer(E.getAs<CFGInitializer>()->getInitializer(), Pred);
  199. return;
  200. case CFGElement::AutomaticObjectDtor:
  201. case CFGElement::BaseDtor:
  202. case CFGElement::MemberDtor:
  203. case CFGElement::TemporaryDtor:
  204. ProcessImplicitDtor(*E.getAs<CFGImplicitDtor>(), Pred);
  205. return;
  206. }
  207. currBldrCtx = 0;
  208. }
  209. static bool shouldRemoveDeadBindings(AnalysisManager &AMgr,
  210. const CFGStmt S,
  211. const ExplodedNode *Pred,
  212. const LocationContext *LC) {
  213. // Are we never purging state values?
  214. if (AMgr.options.AnalysisPurgeOpt == PurgeNone)
  215. return false;
  216. // Is this the beginning of a basic block?
  217. if (isa<BlockEntrance>(Pred->getLocation()))
  218. return true;
  219. // Is this on a non-expression?
  220. if (!isa<Expr>(S.getStmt()))
  221. return true;
  222. // Run before processing a call.
  223. if (CallEvent::isCallStmt(S.getStmt()))
  224. return true;
  225. // Is this an expression that is consumed by another expression? If so,
  226. // postpone cleaning out the state.
  227. ParentMap &PM = LC->getAnalysisDeclContext()->getParentMap();
  228. return !PM.isConsumedExpr(cast<Expr>(S.getStmt()));
  229. }
  230. void ExprEngine::removeDead(ExplodedNode *Pred, ExplodedNodeSet &Out,
  231. const Stmt *ReferenceStmt,
  232. const LocationContext *LC,
  233. const Stmt *DiagnosticStmt,
  234. ProgramPoint::Kind K) {
  235. assert((K == ProgramPoint::PreStmtPurgeDeadSymbolsKind ||
  236. ReferenceStmt == 0 || isa<ReturnStmt>(ReferenceStmt))
  237. && "PostStmt is not generally supported by the SymbolReaper yet");
  238. assert(LC && "Must pass the current (or expiring) LocationContext");
  239. if (!DiagnosticStmt) {
  240. DiagnosticStmt = ReferenceStmt;
  241. assert(DiagnosticStmt && "Required for clearing a LocationContext");
  242. }
  243. NumRemoveDeadBindings++;
  244. ProgramStateRef CleanedState = Pred->getState();
  245. // LC is the location context being destroyed, but SymbolReaper wants a
  246. // location context that is still live. (If this is the top-level stack
  247. // frame, this will be null.)
  248. if (!ReferenceStmt) {
  249. assert(K == ProgramPoint::PostStmtPurgeDeadSymbolsKind &&
  250. "Use PostStmtPurgeDeadSymbolsKind for clearing a LocationContext");
  251. LC = LC->getParent();
  252. }
  253. const StackFrameContext *SFC = LC ? LC->getCurrentStackFrame() : 0;
  254. SymbolReaper SymReaper(SFC, ReferenceStmt, SymMgr, getStoreManager());
  255. getCheckerManager().runCheckersForLiveSymbols(CleanedState, SymReaper);
  256. // Create a state in which dead bindings are removed from the environment
  257. // and the store. TODO: The function should just return new env and store,
  258. // not a new state.
  259. CleanedState = StateMgr.removeDeadBindings(CleanedState, SFC, SymReaper);
  260. // Process any special transfer function for dead symbols.
  261. // A tag to track convenience transitions, which can be removed at cleanup.
  262. static SimpleProgramPointTag cleanupTag("ExprEngine : Clean Node");
  263. if (!SymReaper.hasDeadSymbols()) {
  264. // Generate a CleanedNode that has the environment and store cleaned
  265. // up. Since no symbols are dead, we can optimize and not clean out
  266. // the constraint manager.
  267. StmtNodeBuilder Bldr(Pred, Out, *currBldrCtx);
  268. Bldr.generateNode(DiagnosticStmt, Pred, CleanedState, &cleanupTag, K);
  269. } else {
  270. // Call checkers with the non-cleaned state so that they could query the
  271. // values of the soon to be dead symbols.
  272. ExplodedNodeSet CheckedSet;
  273. getCheckerManager().runCheckersForDeadSymbols(CheckedSet, Pred, SymReaper,
  274. DiagnosticStmt, *this, K);
  275. // For each node in CheckedSet, generate CleanedNodes that have the
  276. // environment, the store, and the constraints cleaned up but have the
  277. // user-supplied states as the predecessors.
  278. StmtNodeBuilder Bldr(CheckedSet, Out, *currBldrCtx);
  279. for (ExplodedNodeSet::const_iterator
  280. I = CheckedSet.begin(), E = CheckedSet.end(); I != E; ++I) {
  281. ProgramStateRef CheckerState = (*I)->getState();
  282. // The constraint manager has not been cleaned up yet, so clean up now.
  283. CheckerState = getConstraintManager().removeDeadBindings(CheckerState,
  284. SymReaper);
  285. assert(StateMgr.haveEqualEnvironments(CheckerState, Pred->getState()) &&
  286. "Checkers are not allowed to modify the Environment as a part of "
  287. "checkDeadSymbols processing.");
  288. assert(StateMgr.haveEqualStores(CheckerState, Pred->getState()) &&
  289. "Checkers are not allowed to modify the Store as a part of "
  290. "checkDeadSymbols processing.");
  291. // Create a state based on CleanedState with CheckerState GDM and
  292. // generate a transition to that state.
  293. ProgramStateRef CleanedCheckerSt =
  294. StateMgr.getPersistentStateWithGDM(CleanedState, CheckerState);
  295. Bldr.generateNode(DiagnosticStmt, *I, CleanedCheckerSt, &cleanupTag, K);
  296. }
  297. }
  298. }
  299. void ExprEngine::ProcessStmt(const CFGStmt S,
  300. ExplodedNode *Pred) {
  301. // Reclaim any unnecessary nodes in the ExplodedGraph.
  302. G.reclaimRecentlyAllocatedNodes();
  303. const Stmt *currStmt = S.getStmt();
  304. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  305. currStmt->getLocStart(),
  306. "Error evaluating statement");
  307. // Remove dead bindings and symbols.
  308. ExplodedNodeSet CleanedStates;
  309. if (shouldRemoveDeadBindings(AMgr, S, Pred, Pred->getLocationContext())){
  310. removeDead(Pred, CleanedStates, currStmt, Pred->getLocationContext());
  311. } else
  312. CleanedStates.Add(Pred);
  313. // Visit the statement.
  314. ExplodedNodeSet Dst;
  315. for (ExplodedNodeSet::iterator I = CleanedStates.begin(),
  316. E = CleanedStates.end(); I != E; ++I) {
  317. ExplodedNodeSet DstI;
  318. // Visit the statement.
  319. Visit(currStmt, *I, DstI);
  320. Dst.insert(DstI);
  321. }
  322. // Enqueue the new nodes onto the work list.
  323. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  324. }
  325. void ExprEngine::ProcessInitializer(const CFGInitializer Init,
  326. ExplodedNode *Pred) {
  327. const CXXCtorInitializer *BMI = Init.getInitializer();
  328. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  329. BMI->getSourceLocation(),
  330. "Error evaluating initializer");
  331. // We don't clean up dead bindings here.
  332. const StackFrameContext *stackFrame =
  333. cast<StackFrameContext>(Pred->getLocationContext());
  334. const CXXConstructorDecl *decl =
  335. cast<CXXConstructorDecl>(stackFrame->getDecl());
  336. ProgramStateRef State = Pred->getState();
  337. SVal thisVal = State->getSVal(svalBuilder.getCXXThis(decl, stackFrame));
  338. PostInitializer PP(BMI, stackFrame);
  339. ExplodedNodeSet Tmp(Pred);
  340. // Evaluate the initializer, if necessary
  341. if (BMI->isAnyMemberInitializer()) {
  342. // Constructors build the object directly in the field,
  343. // but non-objects must be copied in from the initializer.
  344. const Expr *Init = BMI->getInit()->IgnoreImplicit();
  345. if (!isa<CXXConstructExpr>(Init)) {
  346. SVal FieldLoc;
  347. if (BMI->isIndirectMemberInitializer())
  348. FieldLoc = State->getLValue(BMI->getIndirectMember(), thisVal);
  349. else
  350. FieldLoc = State->getLValue(BMI->getMember(), thisVal);
  351. SVal InitVal = State->getSVal(BMI->getInit(), stackFrame);
  352. Tmp.clear();
  353. evalBind(Tmp, Init, Pred, FieldLoc, InitVal, /*isInit=*/true, &PP);
  354. }
  355. } else {
  356. assert(BMI->isBaseInitializer() || BMI->isDelegatingInitializer());
  357. // We already did all the work when visiting the CXXConstructExpr.
  358. }
  359. // Construct PostInitializer nodes whether the state changed or not,
  360. // so that the diagnostics don't get confused.
  361. ExplodedNodeSet Dst;
  362. NodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
  363. for (ExplodedNodeSet::iterator I = Tmp.begin(), E = Tmp.end(); I != E; ++I) {
  364. ExplodedNode *N = *I;
  365. Bldr.generateNode(PP, N->getState(), N);
  366. }
  367. // Enqueue the new nodes onto the work list.
  368. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  369. }
  370. void ExprEngine::ProcessImplicitDtor(const CFGImplicitDtor D,
  371. ExplodedNode *Pred) {
  372. ExplodedNodeSet Dst;
  373. switch (D.getKind()) {
  374. case CFGElement::AutomaticObjectDtor:
  375. ProcessAutomaticObjDtor(cast<CFGAutomaticObjDtor>(D), Pred, Dst);
  376. break;
  377. case CFGElement::BaseDtor:
  378. ProcessBaseDtor(cast<CFGBaseDtor>(D), Pred, Dst);
  379. break;
  380. case CFGElement::MemberDtor:
  381. ProcessMemberDtor(cast<CFGMemberDtor>(D), Pred, Dst);
  382. break;
  383. case CFGElement::TemporaryDtor:
  384. ProcessTemporaryDtor(cast<CFGTemporaryDtor>(D), Pred, Dst);
  385. break;
  386. default:
  387. llvm_unreachable("Unexpected dtor kind.");
  388. }
  389. // Enqueue the new nodes onto the work list.
  390. Engine.enqueue(Dst, currBldrCtx->getBlock(), currStmtIdx);
  391. }
  392. void ExprEngine::ProcessAutomaticObjDtor(const CFGAutomaticObjDtor Dtor,
  393. ExplodedNode *Pred,
  394. ExplodedNodeSet &Dst) {
  395. ProgramStateRef state = Pred->getState();
  396. const VarDecl *varDecl = Dtor.getVarDecl();
  397. QualType varType = varDecl->getType();
  398. if (const ReferenceType *refType = varType->getAs<ReferenceType>())
  399. varType = refType->getPointeeType();
  400. Loc dest = state->getLValue(varDecl, Pred->getLocationContext());
  401. VisitCXXDestructor(varType, cast<loc::MemRegionVal>(dest).getRegion(),
  402. Dtor.getTriggerStmt(), /*IsBase=*/false, Pred, Dst);
  403. }
  404. void ExprEngine::ProcessBaseDtor(const CFGBaseDtor D,
  405. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  406. const LocationContext *LCtx = Pred->getLocationContext();
  407. ProgramStateRef State = Pred->getState();
  408. const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
  409. Loc ThisPtr = getSValBuilder().getCXXThis(CurDtor,
  410. LCtx->getCurrentStackFrame());
  411. SVal ThisVal = Pred->getState()->getSVal(ThisPtr);
  412. // Create the base object region.
  413. QualType BaseTy = D.getBaseSpecifier()->getType();
  414. SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy);
  415. VisitCXXDestructor(BaseTy, cast<loc::MemRegionVal>(BaseVal).getRegion(),
  416. CurDtor->getBody(), /*IsBase=*/true, Pred, Dst);
  417. }
  418. void ExprEngine::ProcessMemberDtor(const CFGMemberDtor D,
  419. ExplodedNode *Pred, ExplodedNodeSet &Dst) {
  420. const FieldDecl *Member = D.getFieldDecl();
  421. ProgramStateRef State = Pred->getState();
  422. const LocationContext *LCtx = Pred->getLocationContext();
  423. const CXXDestructorDecl *CurDtor = cast<CXXDestructorDecl>(LCtx->getDecl());
  424. Loc ThisVal = getSValBuilder().getCXXThis(CurDtor,
  425. LCtx->getCurrentStackFrame());
  426. SVal FieldVal = State->getLValue(Member, cast<Loc>(State->getSVal(ThisVal)));
  427. VisitCXXDestructor(Member->getType(),
  428. cast<loc::MemRegionVal>(FieldVal).getRegion(),
  429. CurDtor->getBody(), /*IsBase=*/false, Pred, Dst);
  430. }
  431. void ExprEngine::ProcessTemporaryDtor(const CFGTemporaryDtor D,
  432. ExplodedNode *Pred,
  433. ExplodedNodeSet &Dst) {}
  434. void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
  435. ExplodedNodeSet &DstTop) {
  436. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  437. S->getLocStart(),
  438. "Error evaluating statement");
  439. ExplodedNodeSet Dst;
  440. StmtNodeBuilder Bldr(Pred, DstTop, *currBldrCtx);
  441. assert(!isa<Expr>(S) || S == cast<Expr>(S)->IgnoreParens());
  442. switch (S->getStmtClass()) {
  443. // C++ and ARC stuff we don't support yet.
  444. case Expr::ObjCIndirectCopyRestoreExprClass:
  445. case Stmt::CXXDependentScopeMemberExprClass:
  446. case Stmt::CXXPseudoDestructorExprClass:
  447. case Stmt::CXXTryStmtClass:
  448. case Stmt::CXXTypeidExprClass:
  449. case Stmt::CXXUuidofExprClass:
  450. case Stmt::CXXUnresolvedConstructExprClass:
  451. case Stmt::DependentScopeDeclRefExprClass:
  452. case Stmt::UnaryTypeTraitExprClass:
  453. case Stmt::BinaryTypeTraitExprClass:
  454. case Stmt::TypeTraitExprClass:
  455. case Stmt::ArrayTypeTraitExprClass:
  456. case Stmt::ExpressionTraitExprClass:
  457. case Stmt::UnresolvedLookupExprClass:
  458. case Stmt::UnresolvedMemberExprClass:
  459. case Stmt::CXXNoexceptExprClass:
  460. case Stmt::PackExpansionExprClass:
  461. case Stmt::SubstNonTypeTemplateParmPackExprClass:
  462. case Stmt::FunctionParmPackExprClass:
  463. case Stmt::SEHTryStmtClass:
  464. case Stmt::SEHExceptStmtClass:
  465. case Stmt::LambdaExprClass:
  466. case Stmt::SEHFinallyStmtClass: {
  467. const ExplodedNode *node = Bldr.generateSink(S, Pred, Pred->getState());
  468. Engine.addAbortedBlock(node, currBldrCtx->getBlock());
  469. break;
  470. }
  471. case Stmt::ParenExprClass:
  472. llvm_unreachable("ParenExprs already handled.");
  473. case Stmt::GenericSelectionExprClass:
  474. llvm_unreachable("GenericSelectionExprs already handled.");
  475. // Cases that should never be evaluated simply because they shouldn't
  476. // appear in the CFG.
  477. case Stmt::BreakStmtClass:
  478. case Stmt::CaseStmtClass:
  479. case Stmt::CompoundStmtClass:
  480. case Stmt::ContinueStmtClass:
  481. case Stmt::CXXForRangeStmtClass:
  482. case Stmt::DefaultStmtClass:
  483. case Stmt::DoStmtClass:
  484. case Stmt::ForStmtClass:
  485. case Stmt::GotoStmtClass:
  486. case Stmt::IfStmtClass:
  487. case Stmt::IndirectGotoStmtClass:
  488. case Stmt::LabelStmtClass:
  489. case Stmt::AttributedStmtClass:
  490. case Stmt::NoStmtClass:
  491. case Stmt::NullStmtClass:
  492. case Stmt::SwitchStmtClass:
  493. case Stmt::WhileStmtClass:
  494. case Expr::MSDependentExistsStmtClass:
  495. llvm_unreachable("Stmt should not be in analyzer evaluation loop");
  496. case Stmt::ObjCSubscriptRefExprClass:
  497. case Stmt::ObjCPropertyRefExprClass:
  498. llvm_unreachable("These are handled by PseudoObjectExpr");
  499. case Stmt::GNUNullExprClass: {
  500. // GNU __null is a pointer-width integer, not an actual pointer.
  501. ProgramStateRef state = Pred->getState();
  502. state = state->BindExpr(S, Pred->getLocationContext(),
  503. svalBuilder.makeIntValWithPtrWidth(0, false));
  504. Bldr.generateNode(S, Pred, state);
  505. break;
  506. }
  507. case Stmt::ObjCAtSynchronizedStmtClass:
  508. Bldr.takeNodes(Pred);
  509. VisitObjCAtSynchronizedStmt(cast<ObjCAtSynchronizedStmt>(S), Pred, Dst);
  510. Bldr.addNodes(Dst);
  511. break;
  512. case Stmt::ExprWithCleanupsClass:
  513. // Handled due to fully linearised CFG.
  514. break;
  515. // Cases not handled yet; but will handle some day.
  516. case Stmt::DesignatedInitExprClass:
  517. case Stmt::ExtVectorElementExprClass:
  518. case Stmt::ImaginaryLiteralClass:
  519. case Stmt::ObjCAtCatchStmtClass:
  520. case Stmt::ObjCAtFinallyStmtClass:
  521. case Stmt::ObjCAtTryStmtClass:
  522. case Stmt::ObjCAutoreleasePoolStmtClass:
  523. case Stmt::ObjCEncodeExprClass:
  524. case Stmt::ObjCIsaExprClass:
  525. case Stmt::ObjCProtocolExprClass:
  526. case Stmt::ObjCSelectorExprClass:
  527. case Stmt::ParenListExprClass:
  528. case Stmt::PredefinedExprClass:
  529. case Stmt::ShuffleVectorExprClass:
  530. case Stmt::VAArgExprClass:
  531. case Stmt::CUDAKernelCallExprClass:
  532. case Stmt::OpaqueValueExprClass:
  533. case Stmt::AsTypeExprClass:
  534. case Stmt::AtomicExprClass:
  535. // Fall through.
  536. // Cases we intentionally don't evaluate, since they don't need
  537. // to be explicitly evaluated.
  538. case Stmt::AddrLabelExprClass:
  539. case Stmt::IntegerLiteralClass:
  540. case Stmt::CharacterLiteralClass:
  541. case Stmt::ImplicitValueInitExprClass:
  542. case Stmt::CXXScalarValueInitExprClass:
  543. case Stmt::CXXBoolLiteralExprClass:
  544. case Stmt::ObjCBoolLiteralExprClass:
  545. case Stmt::FloatingLiteralClass:
  546. case Stmt::SizeOfPackExprClass:
  547. case Stmt::StringLiteralClass:
  548. case Stmt::ObjCStringLiteralClass:
  549. case Stmt::CXXBindTemporaryExprClass:
  550. case Stmt::SubstNonTypeTemplateParmExprClass:
  551. case Stmt::CXXNullPtrLiteralExprClass: {
  552. Bldr.takeNodes(Pred);
  553. ExplodedNodeSet preVisit;
  554. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  555. getCheckerManager().runCheckersForPostStmt(Dst, preVisit, S, *this);
  556. Bldr.addNodes(Dst);
  557. break;
  558. }
  559. case Stmt::CXXDefaultArgExprClass: {
  560. Bldr.takeNodes(Pred);
  561. ExplodedNodeSet PreVisit;
  562. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  563. ExplodedNodeSet Tmp;
  564. StmtNodeBuilder Bldr2(PreVisit, Tmp, *currBldrCtx);
  565. const LocationContext *LCtx = Pred->getLocationContext();
  566. const Expr *ArgE = cast<CXXDefaultArgExpr>(S)->getExpr();
  567. // Avoid creating and destroying a lot of APSInts.
  568. SVal V;
  569. llvm::APSInt Result;
  570. for (ExplodedNodeSet::iterator I = PreVisit.begin(), E = PreVisit.end();
  571. I != E; ++I) {
  572. ProgramStateRef State = (*I)->getState();
  573. if (ArgE->EvaluateAsInt(Result, getContext()))
  574. V = svalBuilder.makeIntVal(Result);
  575. else
  576. V = State->getSVal(ArgE, LCtx);
  577. State = State->BindExpr(S, LCtx, V);
  578. Bldr2.generateNode(S, *I, State);
  579. }
  580. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
  581. Bldr.addNodes(Dst);
  582. break;
  583. }
  584. case Expr::ObjCArrayLiteralClass:
  585. case Expr::ObjCDictionaryLiteralClass:
  586. // FIXME: explicitly model with a region and the actual contents
  587. // of the container. For now, conjure a symbol.
  588. case Expr::ObjCBoxedExprClass: {
  589. Bldr.takeNodes(Pred);
  590. ExplodedNodeSet preVisit;
  591. getCheckerManager().runCheckersForPreStmt(preVisit, Pred, S, *this);
  592. ExplodedNodeSet Tmp;
  593. StmtNodeBuilder Bldr2(preVisit, Tmp, *currBldrCtx);
  594. const Expr *Ex = cast<Expr>(S);
  595. QualType resultType = Ex->getType();
  596. for (ExplodedNodeSet::iterator it = preVisit.begin(), et = preVisit.end();
  597. it != et; ++it) {
  598. ExplodedNode *N = *it;
  599. const LocationContext *LCtx = N->getLocationContext();
  600. SVal result = svalBuilder.conjureSymbolVal(0, Ex, LCtx, resultType,
  601. currBldrCtx->blockCount());
  602. ProgramStateRef state = N->getState()->BindExpr(Ex, LCtx, result);
  603. Bldr2.generateNode(S, N, state);
  604. }
  605. getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
  606. Bldr.addNodes(Dst);
  607. break;
  608. }
  609. case Stmt::ArraySubscriptExprClass:
  610. Bldr.takeNodes(Pred);
  611. VisitLvalArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Pred, Dst);
  612. Bldr.addNodes(Dst);
  613. break;
  614. case Stmt::GCCAsmStmtClass:
  615. Bldr.takeNodes(Pred);
  616. VisitGCCAsmStmt(cast<GCCAsmStmt>(S), Pred, Dst);
  617. Bldr.addNodes(Dst);
  618. break;
  619. case Stmt::MSAsmStmtClass:
  620. Bldr.takeNodes(Pred);
  621. VisitMSAsmStmt(cast<MSAsmStmt>(S), Pred, Dst);
  622. Bldr.addNodes(Dst);
  623. break;
  624. case Stmt::BlockExprClass:
  625. Bldr.takeNodes(Pred);
  626. VisitBlockExpr(cast<BlockExpr>(S), Pred, Dst);
  627. Bldr.addNodes(Dst);
  628. break;
  629. case Stmt::BinaryOperatorClass: {
  630. const BinaryOperator* B = cast<BinaryOperator>(S);
  631. if (B->isLogicalOp()) {
  632. Bldr.takeNodes(Pred);
  633. VisitLogicalExpr(B, Pred, Dst);
  634. Bldr.addNodes(Dst);
  635. break;
  636. }
  637. else if (B->getOpcode() == BO_Comma) {
  638. ProgramStateRef state = Pred->getState();
  639. Bldr.generateNode(B, Pred,
  640. state->BindExpr(B, Pred->getLocationContext(),
  641. state->getSVal(B->getRHS(),
  642. Pred->getLocationContext())));
  643. break;
  644. }
  645. Bldr.takeNodes(Pred);
  646. if (AMgr.options.eagerlyAssumeBinOpBifurcation &&
  647. (B->isRelationalOp() || B->isEqualityOp())) {
  648. ExplodedNodeSet Tmp;
  649. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Tmp);
  650. evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, cast<Expr>(S));
  651. }
  652. else
  653. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  654. Bldr.addNodes(Dst);
  655. break;
  656. }
  657. case Stmt::CXXOperatorCallExprClass: {
  658. const CXXOperatorCallExpr *OCE = cast<CXXOperatorCallExpr>(S);
  659. // For instance method operators, make sure the 'this' argument has a
  660. // valid region.
  661. const Decl *Callee = OCE->getCalleeDecl();
  662. if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
  663. if (MD->isInstance()) {
  664. ProgramStateRef State = Pred->getState();
  665. const LocationContext *LCtx = Pred->getLocationContext();
  666. ProgramStateRef NewState =
  667. createTemporaryRegionIfNeeded(State, LCtx, OCE->getArg(0));
  668. if (NewState != State)
  669. Pred = Bldr.generateNode(OCE, Pred, NewState, /*Tag=*/0,
  670. ProgramPoint::PreStmtKind);
  671. }
  672. }
  673. // FALLTHROUGH
  674. }
  675. case Stmt::CallExprClass:
  676. case Stmt::CXXMemberCallExprClass:
  677. case Stmt::UserDefinedLiteralClass: {
  678. Bldr.takeNodes(Pred);
  679. VisitCallExpr(cast<CallExpr>(S), Pred, Dst);
  680. Bldr.addNodes(Dst);
  681. break;
  682. }
  683. case Stmt::CXXCatchStmtClass: {
  684. Bldr.takeNodes(Pred);
  685. VisitCXXCatchStmt(cast<CXXCatchStmt>(S), Pred, Dst);
  686. Bldr.addNodes(Dst);
  687. break;
  688. }
  689. case Stmt::CXXTemporaryObjectExprClass:
  690. case Stmt::CXXConstructExprClass: {
  691. Bldr.takeNodes(Pred);
  692. VisitCXXConstructExpr(cast<CXXConstructExpr>(S), Pred, Dst);
  693. Bldr.addNodes(Dst);
  694. break;
  695. }
  696. case Stmt::CXXNewExprClass: {
  697. Bldr.takeNodes(Pred);
  698. ExplodedNodeSet PostVisit;
  699. VisitCXXNewExpr(cast<CXXNewExpr>(S), Pred, PostVisit);
  700. getCheckerManager().runCheckersForPostStmt(Dst, PostVisit, S, *this);
  701. Bldr.addNodes(Dst);
  702. break;
  703. }
  704. case Stmt::CXXDeleteExprClass: {
  705. Bldr.takeNodes(Pred);
  706. ExplodedNodeSet PreVisit;
  707. const CXXDeleteExpr *CDE = cast<CXXDeleteExpr>(S);
  708. getCheckerManager().runCheckersForPreStmt(PreVisit, Pred, S, *this);
  709. for (ExplodedNodeSet::iterator i = PreVisit.begin(),
  710. e = PreVisit.end(); i != e ; ++i)
  711. VisitCXXDeleteExpr(CDE, *i, Dst);
  712. Bldr.addNodes(Dst);
  713. break;
  714. }
  715. // FIXME: ChooseExpr is really a constant. We need to fix
  716. // the CFG do not model them as explicit control-flow.
  717. case Stmt::ChooseExprClass: { // __builtin_choose_expr
  718. Bldr.takeNodes(Pred);
  719. const ChooseExpr *C = cast<ChooseExpr>(S);
  720. VisitGuardedExpr(C, C->getLHS(), C->getRHS(), Pred, Dst);
  721. Bldr.addNodes(Dst);
  722. break;
  723. }
  724. case Stmt::CompoundAssignOperatorClass:
  725. Bldr.takeNodes(Pred);
  726. VisitBinaryOperator(cast<BinaryOperator>(S), Pred, Dst);
  727. Bldr.addNodes(Dst);
  728. break;
  729. case Stmt::CompoundLiteralExprClass:
  730. Bldr.takeNodes(Pred);
  731. VisitCompoundLiteralExpr(cast<CompoundLiteralExpr>(S), Pred, Dst);
  732. Bldr.addNodes(Dst);
  733. break;
  734. case Stmt::BinaryConditionalOperatorClass:
  735. case Stmt::ConditionalOperatorClass: { // '?' operator
  736. Bldr.takeNodes(Pred);
  737. const AbstractConditionalOperator *C
  738. = cast<AbstractConditionalOperator>(S);
  739. VisitGuardedExpr(C, C->getTrueExpr(), C->getFalseExpr(), Pred, Dst);
  740. Bldr.addNodes(Dst);
  741. break;
  742. }
  743. case Stmt::CXXThisExprClass:
  744. Bldr.takeNodes(Pred);
  745. VisitCXXThisExpr(cast<CXXThisExpr>(S), Pred, Dst);
  746. Bldr.addNodes(Dst);
  747. break;
  748. case Stmt::DeclRefExprClass: {
  749. Bldr.takeNodes(Pred);
  750. const DeclRefExpr *DE = cast<DeclRefExpr>(S);
  751. VisitCommonDeclRefExpr(DE, DE->getDecl(), Pred, Dst);
  752. Bldr.addNodes(Dst);
  753. break;
  754. }
  755. case Stmt::DeclStmtClass:
  756. Bldr.takeNodes(Pred);
  757. VisitDeclStmt(cast<DeclStmt>(S), Pred, Dst);
  758. Bldr.addNodes(Dst);
  759. break;
  760. case Stmt::ImplicitCastExprClass:
  761. case Stmt::CStyleCastExprClass:
  762. case Stmt::CXXStaticCastExprClass:
  763. case Stmt::CXXDynamicCastExprClass:
  764. case Stmt::CXXReinterpretCastExprClass:
  765. case Stmt::CXXConstCastExprClass:
  766. case Stmt::CXXFunctionalCastExprClass:
  767. case Stmt::ObjCBridgedCastExprClass: {
  768. Bldr.takeNodes(Pred);
  769. const CastExpr *C = cast<CastExpr>(S);
  770. // Handle the previsit checks.
  771. ExplodedNodeSet dstPrevisit;
  772. getCheckerManager().runCheckersForPreStmt(dstPrevisit, Pred, C, *this);
  773. // Handle the expression itself.
  774. ExplodedNodeSet dstExpr;
  775. for (ExplodedNodeSet::iterator i = dstPrevisit.begin(),
  776. e = dstPrevisit.end(); i != e ; ++i) {
  777. VisitCast(C, C->getSubExpr(), *i, dstExpr);
  778. }
  779. // Handle the postvisit checks.
  780. getCheckerManager().runCheckersForPostStmt(Dst, dstExpr, C, *this);
  781. Bldr.addNodes(Dst);
  782. break;
  783. }
  784. case Expr::MaterializeTemporaryExprClass: {
  785. Bldr.takeNodes(Pred);
  786. const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
  787. CreateCXXTemporaryObject(MTE, Pred, Dst);
  788. Bldr.addNodes(Dst);
  789. break;
  790. }
  791. case Stmt::InitListExprClass:
  792. Bldr.takeNodes(Pred);
  793. VisitInitListExpr(cast<InitListExpr>(S), Pred, Dst);
  794. Bldr.addNodes(Dst);
  795. break;
  796. case Stmt::MemberExprClass:
  797. Bldr.takeNodes(Pred);
  798. VisitMemberExpr(cast<MemberExpr>(S), Pred, Dst);
  799. Bldr.addNodes(Dst);
  800. break;
  801. case Stmt::ObjCIvarRefExprClass:
  802. Bldr.takeNodes(Pred);
  803. VisitLvalObjCIvarRefExpr(cast<ObjCIvarRefExpr>(S), Pred, Dst);
  804. Bldr.addNodes(Dst);
  805. break;
  806. case Stmt::ObjCForCollectionStmtClass:
  807. Bldr.takeNodes(Pred);
  808. VisitObjCForCollectionStmt(cast<ObjCForCollectionStmt>(S), Pred, Dst);
  809. Bldr.addNodes(Dst);
  810. break;
  811. case Stmt::ObjCMessageExprClass:
  812. Bldr.takeNodes(Pred);
  813. VisitObjCMessage(cast<ObjCMessageExpr>(S), Pred, Dst);
  814. Bldr.addNodes(Dst);
  815. break;
  816. case Stmt::ObjCAtThrowStmtClass:
  817. case Stmt::CXXThrowExprClass:
  818. // FIXME: This is not complete. We basically treat @throw as
  819. // an abort.
  820. Bldr.generateSink(S, Pred, Pred->getState());
  821. break;
  822. case Stmt::ReturnStmtClass:
  823. Bldr.takeNodes(Pred);
  824. VisitReturnStmt(cast<ReturnStmt>(S), Pred, Dst);
  825. Bldr.addNodes(Dst);
  826. break;
  827. case Stmt::OffsetOfExprClass:
  828. Bldr.takeNodes(Pred);
  829. VisitOffsetOfExpr(cast<OffsetOfExpr>(S), Pred, Dst);
  830. Bldr.addNodes(Dst);
  831. break;
  832. case Stmt::UnaryExprOrTypeTraitExprClass:
  833. Bldr.takeNodes(Pred);
  834. VisitUnaryExprOrTypeTraitExpr(cast<UnaryExprOrTypeTraitExpr>(S),
  835. Pred, Dst);
  836. Bldr.addNodes(Dst);
  837. break;
  838. case Stmt::StmtExprClass: {
  839. const StmtExpr *SE = cast<StmtExpr>(S);
  840. if (SE->getSubStmt()->body_empty()) {
  841. // Empty statement expression.
  842. assert(SE->getType() == getContext().VoidTy
  843. && "Empty statement expression must have void type.");
  844. break;
  845. }
  846. if (Expr *LastExpr = dyn_cast<Expr>(*SE->getSubStmt()->body_rbegin())) {
  847. ProgramStateRef state = Pred->getState();
  848. Bldr.generateNode(SE, Pred,
  849. state->BindExpr(SE, Pred->getLocationContext(),
  850. state->getSVal(LastExpr,
  851. Pred->getLocationContext())));
  852. }
  853. break;
  854. }
  855. case Stmt::UnaryOperatorClass: {
  856. Bldr.takeNodes(Pred);
  857. const UnaryOperator *U = cast<UnaryOperator>(S);
  858. if (AMgr.options.eagerlyAssumeBinOpBifurcation && (U->getOpcode() == UO_LNot)) {
  859. ExplodedNodeSet Tmp;
  860. VisitUnaryOperator(U, Pred, Tmp);
  861. evalEagerlyAssumeBinOpBifurcation(Dst, Tmp, U);
  862. }
  863. else
  864. VisitUnaryOperator(U, Pred, Dst);
  865. Bldr.addNodes(Dst);
  866. break;
  867. }
  868. case Stmt::PseudoObjectExprClass: {
  869. Bldr.takeNodes(Pred);
  870. ProgramStateRef state = Pred->getState();
  871. const PseudoObjectExpr *PE = cast<PseudoObjectExpr>(S);
  872. if (const Expr *Result = PE->getResultExpr()) {
  873. SVal V = state->getSVal(Result, Pred->getLocationContext());
  874. Bldr.generateNode(S, Pred,
  875. state->BindExpr(S, Pred->getLocationContext(), V));
  876. }
  877. else
  878. Bldr.generateNode(S, Pred,
  879. state->BindExpr(S, Pred->getLocationContext(),
  880. UnknownVal()));
  881. Bldr.addNodes(Dst);
  882. break;
  883. }
  884. }
  885. }
  886. bool ExprEngine::replayWithoutInlining(ExplodedNode *N,
  887. const LocationContext *CalleeLC) {
  888. const StackFrameContext *CalleeSF = CalleeLC->getCurrentStackFrame();
  889. const StackFrameContext *CallerSF = CalleeSF->getParent()->getCurrentStackFrame();
  890. assert(CalleeSF && CallerSF);
  891. ExplodedNode *BeforeProcessingCall = 0;
  892. const Stmt *CE = CalleeSF->getCallSite();
  893. // Find the first node before we started processing the call expression.
  894. while (N) {
  895. ProgramPoint L = N->getLocation();
  896. BeforeProcessingCall = N;
  897. N = N->pred_empty() ? NULL : *(N->pred_begin());
  898. // Skip the nodes corresponding to the inlined code.
  899. if (L.getLocationContext()->getCurrentStackFrame() != CallerSF)
  900. continue;
  901. // We reached the caller. Find the node right before we started
  902. // processing the call.
  903. if (L.isPurgeKind())
  904. continue;
  905. if (isa<PreImplicitCall>(&L))
  906. continue;
  907. if (isa<CallEnter>(&L))
  908. continue;
  909. if (const StmtPoint *SP = dyn_cast<StmtPoint>(&L))
  910. if (SP->getStmt() == CE)
  911. continue;
  912. break;
  913. }
  914. if (!BeforeProcessingCall)
  915. return false;
  916. // TODO: Clean up the unneeded nodes.
  917. // Build an Epsilon node from which we will restart the analyzes.
  918. // Note that CE is permitted to be NULL!
  919. ProgramPoint NewNodeLoc =
  920. EpsilonPoint(BeforeProcessingCall->getLocationContext(), CE);
  921. // Add the special flag to GDM to signal retrying with no inlining.
  922. // Note, changing the state ensures that we are not going to cache out.
  923. ProgramStateRef NewNodeState = BeforeProcessingCall->getState();
  924. NewNodeState =
  925. NewNodeState->set<ReplayWithoutInlining>(const_cast<Stmt *>(CE));
  926. // Make the new node a successor of BeforeProcessingCall.
  927. bool IsNew = false;
  928. ExplodedNode *NewNode = G.getNode(NewNodeLoc, NewNodeState, false, &IsNew);
  929. // We cached out at this point. Caching out is common due to us backtracking
  930. // from the inlined function, which might spawn several paths.
  931. if (!IsNew)
  932. return true;
  933. NewNode->addPredecessor(BeforeProcessingCall, G);
  934. // Add the new node to the work list.
  935. Engine.enqueueStmtNode(NewNode, CalleeSF->getCallSiteBlock(),
  936. CalleeSF->getIndex());
  937. NumTimesRetriedWithoutInlining++;
  938. return true;
  939. }
  940. /// Block entrance. (Update counters).
  941. void ExprEngine::processCFGBlockEntrance(const BlockEdge &L,
  942. NodeBuilderWithSinks &nodeBuilder,
  943. ExplodedNode *Pred) {
  944. // FIXME: Refactor this into a checker.
  945. if (nodeBuilder.getContext().blockCount() >= AMgr.options.maxBlockVisitOnPath) {
  946. static SimpleProgramPointTag tag("ExprEngine : Block count exceeded");
  947. const ExplodedNode *Sink =
  948. nodeBuilder.generateSink(Pred->getState(), Pred, &tag);
  949. // Check if we stopped at the top level function or not.
  950. // Root node should have the location context of the top most function.
  951. const LocationContext *CalleeLC = Pred->getLocation().getLocationContext();
  952. const LocationContext *CalleeSF = CalleeLC->getCurrentStackFrame();
  953. const LocationContext *RootLC =
  954. (*G.roots_begin())->getLocation().getLocationContext();
  955. if (RootLC->getCurrentStackFrame() != CalleeSF) {
  956. Engine.FunctionSummaries->markReachedMaxBlockCount(CalleeSF->getDecl());
  957. // Re-run the call evaluation without inlining it, by storing the
  958. // no-inlining policy in the state and enqueuing the new work item on
  959. // the list. Replay should almost never fail. Use the stats to catch it
  960. // if it does.
  961. if ((!AMgr.options.NoRetryExhausted &&
  962. replayWithoutInlining(Pred, CalleeLC)))
  963. return;
  964. NumMaxBlockCountReachedInInlined++;
  965. } else
  966. NumMaxBlockCountReached++;
  967. // Make sink nodes as exhausted(for stats) only if retry failed.
  968. Engine.blocksExhausted.push_back(std::make_pair(L, Sink));
  969. }
  970. }
  971. //===----------------------------------------------------------------------===//
  972. // Branch processing.
  973. //===----------------------------------------------------------------------===//
  974. /// RecoverCastedSymbol - A helper function for ProcessBranch that is used
  975. /// to try to recover some path-sensitivity for casts of symbolic
  976. /// integers that promote their values (which are currently not tracked well).
  977. /// This function returns the SVal bound to Condition->IgnoreCasts if all the
  978. // cast(s) did was sign-extend the original value.
  979. static SVal RecoverCastedSymbol(ProgramStateManager& StateMgr,
  980. ProgramStateRef state,
  981. const Stmt *Condition,
  982. const LocationContext *LCtx,
  983. ASTContext &Ctx) {
  984. const Expr *Ex = dyn_cast<Expr>(Condition);
  985. if (!Ex)
  986. return UnknownVal();
  987. uint64_t bits = 0;
  988. bool bitsInit = false;
  989. while (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) {
  990. QualType T = CE->getType();
  991. if (!T->isIntegerType())
  992. return UnknownVal();
  993. uint64_t newBits = Ctx.getTypeSize(T);
  994. if (!bitsInit || newBits < bits) {
  995. bitsInit = true;
  996. bits = newBits;
  997. }
  998. Ex = CE->getSubExpr();
  999. }
  1000. // We reached a non-cast. Is it a symbolic value?
  1001. QualType T = Ex->getType();
  1002. if (!bitsInit || !T->isIntegerType() || Ctx.getTypeSize(T) > bits)
  1003. return UnknownVal();
  1004. return state->getSVal(Ex, LCtx);
  1005. }
  1006. static const Stmt *ResolveCondition(const Stmt *Condition,
  1007. const CFGBlock *B) {
  1008. if (const Expr *Ex = dyn_cast<Expr>(Condition))
  1009. Condition = Ex->IgnoreParens();
  1010. const BinaryOperator *BO = dyn_cast<BinaryOperator>(Condition);
  1011. if (!BO || !BO->isLogicalOp())
  1012. return Condition;
  1013. // For logical operations, we still have the case where some branches
  1014. // use the traditional "merge" approach and others sink the branch
  1015. // directly into the basic blocks representing the logical operation.
  1016. // We need to distinguish between those two cases here.
  1017. // The invariants are still shifting, but it is possible that the
  1018. // last element in a CFGBlock is not a CFGStmt. Look for the last
  1019. // CFGStmt as the value of the condition.
  1020. CFGBlock::const_reverse_iterator I = B->rbegin(), E = B->rend();
  1021. for (; I != E; ++I) {
  1022. CFGElement Elem = *I;
  1023. CFGStmt *CS = dyn_cast<CFGStmt>(&Elem);
  1024. if (!CS)
  1025. continue;
  1026. if (CS->getStmt() != Condition)
  1027. break;
  1028. return Condition;
  1029. }
  1030. assert(I != E);
  1031. while (Condition) {
  1032. BO = dyn_cast<BinaryOperator>(Condition);
  1033. if (!BO || !BO->isLogicalOp())
  1034. return Condition;
  1035. Condition = BO->getRHS()->IgnoreParens();
  1036. }
  1037. llvm_unreachable("could not resolve condition");
  1038. }
  1039. void ExprEngine::processBranch(const Stmt *Condition, const Stmt *Term,
  1040. NodeBuilderContext& BldCtx,
  1041. ExplodedNode *Pred,
  1042. ExplodedNodeSet &Dst,
  1043. const CFGBlock *DstT,
  1044. const CFGBlock *DstF) {
  1045. currBldrCtx = &BldCtx;
  1046. // Check for NULL conditions; e.g. "for(;;)"
  1047. if (!Condition) {
  1048. BranchNodeBuilder NullCondBldr(Pred, Dst, BldCtx, DstT, DstF);
  1049. NullCondBldr.markInfeasible(false);
  1050. NullCondBldr.generateNode(Pred->getState(), true, Pred);
  1051. return;
  1052. }
  1053. // Resolve the condition in the precense of nested '||' and '&&'.
  1054. if (const Expr *Ex = dyn_cast<Expr>(Condition))
  1055. Condition = Ex->IgnoreParens();
  1056. Condition = ResolveCondition(Condition, BldCtx.getBlock());
  1057. PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
  1058. Condition->getLocStart(),
  1059. "Error evaluating branch");
  1060. ExplodedNodeSet CheckersOutSet;
  1061. getCheckerManager().runCheckersForBranchCondition(Condition, CheckersOutSet,
  1062. Pred, *this);
  1063. // We generated only sinks.
  1064. if (CheckersOutSet.empty())
  1065. return;
  1066. BranchNodeBuilder builder(CheckersOutSet, Dst, BldCtx, DstT, DstF);
  1067. for (NodeBuilder::iterator I = CheckersOutSet.begin(),
  1068. E = CheckersOutSet.end(); E != I; ++I) {
  1069. ExplodedNode *PredI = *I;
  1070. if (PredI->isSink())
  1071. continue;
  1072. ProgramStateRef PrevState = PredI->getState();
  1073. SVal X = PrevState->getSVal(Condition, PredI->getLocationContext());
  1074. if (X.isUnknownOrUndef()) {
  1075. // Give it a chance to recover from unknown.
  1076. if (const Expr *Ex = dyn_cast<Expr>(Condition)) {
  1077. if (Ex->getType()->isIntegerType()) {
  1078. // Try to recover some path-sensitivity. Right now casts of symbolic
  1079. // integers that promote their values are currently not tracked well.
  1080. // If 'Condition' is such an expression, try and recover the
  1081. // underlying value and use that instead.
  1082. SVal recovered = RecoverCastedSymbol(getStateManager(),
  1083. PrevState, Condition,
  1084. PredI->getLocationContext(),
  1085. getContext());
  1086. if (!recovered.isUnknown()) {
  1087. X = recovered;
  1088. }
  1089. }
  1090. }
  1091. }
  1092. // If the condition is still unknown, give up.
  1093. if (X.isUnknownOrUndef()) {
  1094. builder.generateNode(PrevState, true, PredI);
  1095. builder.generateNode(PrevState, false, PredI);
  1096. continue;
  1097. }
  1098. DefinedSVal V = cast<DefinedSVal>(X);
  1099. ProgramStateRef StTrue, StFalse;
  1100. tie(StTrue, StFalse) = PrevState->assume(V);
  1101. // Process the true branch.
  1102. if (builder.isFeasible(true)) {
  1103. if (StTrue)
  1104. builder.generateNode(StTrue, true, PredI);
  1105. else
  1106. builder.markInfeasible(true);
  1107. }
  1108. // Process the false branch.
  1109. if (builder.isFeasible(false)) {
  1110. if (StFalse)
  1111. builder.generateNode(StFalse, false, PredI);
  1112. else
  1113. builder.markInfeasible(false);
  1114. }
  1115. }
  1116. currBldrCtx = 0;
  1117. }
  1118. /// processIndirectGoto - Called by CoreEngine. Used to generate successor
  1119. /// nodes by processing the 'effects' of a computed goto jump.
  1120. void ExprEngine::processIndirectGoto(IndirectGotoNodeBuilder &builder) {
  1121. ProgramStateRef state = builder.getState();
  1122. SVal V = state->getSVal(builder.getTarget(), builder.getLocationContext());
  1123. // Three possibilities:
  1124. //
  1125. // (1) We know the computed label.
  1126. // (2) The label is NULL (or some other constant), or Undefined.
  1127. // (3) We have no clue about the label. Dispatch to all targets.
  1128. //
  1129. typedef IndirectGotoNodeBuilder::iterator iterator;
  1130. if (isa<loc::GotoLabel>(V)) {
  1131. const LabelDecl *L = cast<loc::GotoLabel>(V).getLabel();
  1132. for (iterator I = builder.begin(), E = builder.end(); I != E; ++I) {
  1133. if (I.getLabel() == L) {
  1134. builder.generateNode(I, state);
  1135. return;
  1136. }
  1137. }
  1138. llvm_unreachable("No block with label.");
  1139. }
  1140. if (isa<loc::ConcreteInt>(V) || isa<UndefinedVal>(V)) {
  1141. // Dispatch to the first target and mark it as a sink.
  1142. //ExplodedNode* N = builder.generateNode(builder.begin(), state, true);
  1143. // FIXME: add checker visit.
  1144. // UndefBranches.insert(N);
  1145. return;
  1146. }
  1147. // This is really a catch-all. We don't support symbolics yet.
  1148. // FIXME: Implement dispatch for symbolic pointers.
  1149. for (iterator I=builder.begin(), E=builder.end(); I != E; ++I)
  1150. builder.generateNode(I, state);
  1151. }
  1152. /// ProcessEndPath - Called by CoreEngine. Used to generate end-of-path
  1153. /// nodes when the control reaches the end of a function.
  1154. void ExprEngine::processEndOfFunction(NodeBuilderContext& BC,
  1155. ExplodedNode *Pred) {
  1156. StateMgr.EndPath(Pred->getState());
  1157. ExplodedNodeSet Dst;
  1158. if (Pred->getLocationContext()->inTopFrame()) {
  1159. // Remove dead symbols.
  1160. ExplodedNodeSet AfterRemovedDead;
  1161. removeDeadOnEndOfFunction(BC, Pred, AfterRemovedDead);
  1162. // Notify checkers.
  1163. for (ExplodedNodeSet::iterator I = AfterRemovedDead.begin(),
  1164. E = AfterRemovedDead.end(); I != E; ++I) {
  1165. getCheckerManager().runCheckersForEndFunction(BC, Dst, *I, *this);
  1166. }
  1167. } else {
  1168. getCheckerManager().runCheckersForEndFunction(BC, Dst, Pred, *this);
  1169. }
  1170. Engine.enqueueEndOfFunction(Dst);
  1171. }
  1172. /// ProcessSwitch - Called by CoreEngine. Used to generate successor
  1173. /// nodes by processing the 'effects' of a switch statement.
  1174. void ExprEngine::processSwitch(SwitchNodeBuilder& builder) {
  1175. typedef SwitchNodeBuilder::iterator iterator;
  1176. ProgramStateRef state = builder.getState();
  1177. const Expr *CondE = builder.getCondition();
  1178. SVal CondV_untested = state->getSVal(CondE, builder.getLocationContext());
  1179. if (CondV_untested.isUndef()) {
  1180. //ExplodedNode* N = builder.generateDefaultCaseNode(state, true);
  1181. // FIXME: add checker
  1182. //UndefBranches.insert(N);
  1183. return;
  1184. }
  1185. DefinedOrUnknownSVal CondV = cast<DefinedOrUnknownSVal>(CondV_untested);
  1186. ProgramStateRef DefaultSt = state;
  1187. iterator I = builder.begin(), EI = builder.end();
  1188. bool defaultIsFeasible = I == EI;
  1189. for ( ; I != EI; ++I) {
  1190. // Successor may be pruned out during CFG construction.
  1191. if (!I.getBlock())
  1192. continue;
  1193. const CaseStmt *Case = I.getCase();
  1194. // Evaluate the LHS of the case value.
  1195. llvm::APSInt V1 = Case->getLHS()->EvaluateKnownConstInt(getContext());
  1196. assert(V1.getBitWidth() == getContext().getTypeSize(CondE->getType()));
  1197. // Get the RHS of the case, if it exists.
  1198. llvm::APSInt V2;
  1199. if (const Expr *E = Case->getRHS())
  1200. V2 = E->EvaluateKnownConstInt(getContext());
  1201. else
  1202. V2 = V1;
  1203. // FIXME: Eventually we should replace the logic below with a range
  1204. // comparison, rather than concretize the values within the range.
  1205. // This should be easy once we have "ranges" for NonLVals.
  1206. do {
  1207. nonloc::ConcreteInt CaseVal(getBasicVals().getValue(V1));
  1208. DefinedOrUnknownSVal Res = svalBuilder.evalEQ(DefaultSt ? DefaultSt : state,
  1209. CondV, CaseVal);
  1210. // Now "assume" that the case matches.
  1211. if (ProgramStateRef stateNew = state->assume(Res, true)) {
  1212. builder.generateCaseStmtNode(I, stateNew);
  1213. // If CondV evaluates to a constant, then we know that this
  1214. // is the *only* case that we can take, so stop evaluating the
  1215. // others.
  1216. if (isa<nonloc::ConcreteInt>(CondV))
  1217. return;
  1218. }
  1219. // Now "assume" that the case doesn't match. Add this state
  1220. // to the default state (if it is feasible).
  1221. if (DefaultSt) {
  1222. if (ProgramStateRef stateNew = DefaultSt->assume(Res, false)) {
  1223. defaultIsFeasible = true;
  1224. DefaultSt = stateNew;
  1225. }
  1226. else {
  1227. defaultIsFeasible = false;
  1228. DefaultSt = NULL;
  1229. }
  1230. }
  1231. // Concretize the next value in the range.
  1232. if (V1 == V2)
  1233. break;
  1234. ++V1;
  1235. assert (V1 <= V2);
  1236. } while (true);
  1237. }
  1238. if (!defaultIsFeasible)
  1239. return;
  1240. // If we have switch(enum value), the default branch is not
  1241. // feasible if all of the enum constants not covered by 'case:' statements
  1242. // are not feasible values for the switch condition.
  1243. //
  1244. // Note that this isn't as accurate as it could be. Even if there isn't
  1245. // a case for a particular enum value as long as that enum value isn't
  1246. // feasible then it shouldn't be considered for making 'default:' reachable.
  1247. const SwitchStmt *SS = builder.getSwitch();
  1248. const Expr *CondExpr = SS->getCond()->IgnoreParenImpCasts();
  1249. if (CondExpr->getType()->getAs<EnumType>()) {
  1250. if (SS->isAllEnumCasesCovered())
  1251. return;
  1252. }
  1253. builder.generateDefaultCaseNode(DefaultSt);
  1254. }
  1255. //===----------------------------------------------------------------------===//
  1256. // Transfer functions: Loads and stores.
  1257. //===----------------------------------------------------------------------===//
  1258. void ExprEngine::VisitCommonDeclRefExpr(const Expr *Ex, const NamedDecl *D,
  1259. ExplodedNode *Pred,
  1260. ExplodedNodeSet &Dst) {
  1261. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  1262. ProgramStateRef state = Pred->getState();
  1263. const LocationContext *LCtx = Pred->getLocationContext();
  1264. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1265. assert(Ex->isGLValue());
  1266. SVal V = state->getLValue(VD, Pred->getLocationContext());
  1267. // For references, the 'lvalue' is the pointer address stored in the
  1268. // reference region.
  1269. if (VD->getType()->isReferenceType()) {
  1270. if (const MemRegion *R = V.getAsRegion())
  1271. V = state->getSVal(R);
  1272. else
  1273. V = UnknownVal();
  1274. }
  1275. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0,
  1276. ProgramPoint::PostLValueKind);
  1277. return;
  1278. }
  1279. if (const EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
  1280. assert(!Ex->isGLValue());
  1281. SVal V = svalBuilder.makeIntVal(ED->getInitVal());
  1282. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V));
  1283. return;
  1284. }
  1285. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1286. SVal V = svalBuilder.getFunctionPointer(FD);
  1287. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0,
  1288. ProgramPoint::PostLValueKind);
  1289. return;
  1290. }
  1291. if (isa<FieldDecl>(D)) {
  1292. // FIXME: Compute lvalue of field pointers-to-member.
  1293. // Right now we just use a non-null void pointer, so that it gives proper
  1294. // results in boolean contexts.
  1295. SVal V = svalBuilder.conjureSymbolVal(Ex, LCtx, getContext().VoidPtrTy,
  1296. currBldrCtx->blockCount());
  1297. state = state->assume(cast<DefinedOrUnknownSVal>(V), true);
  1298. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, V), 0,
  1299. ProgramPoint::PostLValueKind);
  1300. return;
  1301. }
  1302. llvm_unreachable("Support for this Decl not implemented.");
  1303. }
  1304. /// VisitArraySubscriptExpr - Transfer function for array accesses
  1305. void ExprEngine::VisitLvalArraySubscriptExpr(const ArraySubscriptExpr *A,
  1306. ExplodedNode *Pred,
  1307. ExplodedNodeSet &Dst){
  1308. const Expr *Base = A->getBase()->IgnoreParens();
  1309. const Expr *Idx = A->getIdx()->IgnoreParens();
  1310. ExplodedNodeSet checkerPreStmt;
  1311. getCheckerManager().runCheckersForPreStmt(checkerPreStmt, Pred, A, *this);
  1312. StmtNodeBuilder Bldr(checkerPreStmt, Dst, *currBldrCtx);
  1313. for (ExplodedNodeSet::iterator it = checkerPreStmt.begin(),
  1314. ei = checkerPreStmt.end(); it != ei; ++it) {
  1315. const LocationContext *LCtx = (*it)->getLocationContext();
  1316. ProgramStateRef state = (*it)->getState();
  1317. SVal V = state->getLValue(A->getType(),
  1318. state->getSVal(Idx, LCtx),
  1319. state->getSVal(Base, LCtx));
  1320. assert(A->isGLValue());
  1321. Bldr.generateNode(A, *it, state->BindExpr(A, LCtx, V), 0,
  1322. ProgramPoint::PostLValueKind);
  1323. }
  1324. }
  1325. /// VisitMemberExpr - Transfer function for member expressions.
  1326. void ExprEngine::VisitMemberExpr(const MemberExpr *M, ExplodedNode *Pred,
  1327. ExplodedNodeSet &TopDst) {
  1328. StmtNodeBuilder Bldr(Pred, TopDst, *currBldrCtx);
  1329. ExplodedNodeSet Dst;
  1330. ValueDecl *Member = M->getMemberDecl();
  1331. // Handle static member variables and enum constants accessed via
  1332. // member syntax.
  1333. if (isa<VarDecl>(Member) || isa<EnumConstantDecl>(Member)) {
  1334. Bldr.takeNodes(Pred);
  1335. VisitCommonDeclRefExpr(M, Member, Pred, Dst);
  1336. Bldr.addNodes(Dst);
  1337. return;
  1338. }
  1339. ProgramStateRef state = Pred->getState();
  1340. const LocationContext *LCtx = Pred->getLocationContext();
  1341. Expr *BaseExpr = M->getBase();
  1342. // Handle C++ method calls.
  1343. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
  1344. if (MD->isInstance())
  1345. state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
  1346. SVal MDVal = svalBuilder.getFunctionPointer(MD);
  1347. state = state->BindExpr(M, LCtx, MDVal);
  1348. Bldr.generateNode(M, Pred, state);
  1349. return;
  1350. }
  1351. // Handle regular struct fields / member variables.
  1352. state = createTemporaryRegionIfNeeded(state, LCtx, BaseExpr);
  1353. SVal baseExprVal = state->getSVal(BaseExpr, LCtx);
  1354. FieldDecl *field = cast<FieldDecl>(Member);
  1355. SVal L = state->getLValue(field, baseExprVal);
  1356. if (M->isGLValue()) {
  1357. if (field->getType()->isReferenceType()) {
  1358. if (const MemRegion *R = L.getAsRegion())
  1359. L = state->getSVal(R);
  1360. else
  1361. L = UnknownVal();
  1362. }
  1363. Bldr.generateNode(M, Pred, state->BindExpr(M, LCtx, L), 0,
  1364. ProgramPoint::PostLValueKind);
  1365. } else {
  1366. Bldr.takeNodes(Pred);
  1367. evalLoad(Dst, M, M, Pred, state, L);
  1368. Bldr.addNodes(Dst);
  1369. }
  1370. }
  1371. namespace {
  1372. class CollectReachableSymbolsCallback : public SymbolVisitor {
  1373. InvalidatedSymbols Symbols;
  1374. public:
  1375. CollectReachableSymbolsCallback(ProgramStateRef State) {}
  1376. const InvalidatedSymbols &getSymbols() const { return Symbols; }
  1377. bool VisitSymbol(SymbolRef Sym) {
  1378. Symbols.insert(Sym);
  1379. return true;
  1380. }
  1381. };
  1382. } // end anonymous namespace
  1383. // A value escapes in three possible cases:
  1384. // (1) We are binding to something that is not a memory region.
  1385. // (2) We are binding to a MemrRegion that does not have stack storage.
  1386. // (3) We are binding to a MemRegion with stack storage that the store
  1387. // does not understand.
  1388. ProgramStateRef ExprEngine::processPointerEscapedOnBind(ProgramStateRef State,
  1389. SVal Loc, SVal Val) {
  1390. // Are we storing to something that causes the value to "escape"?
  1391. bool escapes = true;
  1392. // TODO: Move to StoreManager.
  1393. if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&Loc)) {
  1394. escapes = !regionLoc->getRegion()->hasStackStorage();
  1395. if (!escapes) {
  1396. // To test (3), generate a new state with the binding added. If it is
  1397. // the same state, then it escapes (since the store cannot represent
  1398. // the binding).
  1399. // Do this only if we know that the store is not supposed to generate the
  1400. // same state.
  1401. SVal StoredVal = State->getSVal(regionLoc->getRegion());
  1402. if (StoredVal != Val)
  1403. escapes = (State == (State->bindLoc(*regionLoc, Val)));
  1404. }
  1405. if (!escapes) {
  1406. // Case 4: We do not currently model what happens when a symbol is
  1407. // assigned to a struct field, so be conservative here and let the symbol
  1408. // go. TODO: This could definitely be improved upon.
  1409. escapes = !isa<VarRegion>(regionLoc->getRegion());
  1410. }
  1411. }
  1412. // If our store can represent the binding and we aren't storing to something
  1413. // that doesn't have local storage then just return and have the simulation
  1414. // state continue as is.
  1415. if (!escapes)
  1416. return State;
  1417. // Otherwise, find all symbols referenced by 'val' that we are tracking
  1418. // and stop tracking them.
  1419. CollectReachableSymbolsCallback Scanner =
  1420. State->scanReachableSymbols<CollectReachableSymbolsCallback>(Val);
  1421. const InvalidatedSymbols &EscapedSymbols = Scanner.getSymbols();
  1422. State = getCheckerManager().runCheckersForPointerEscape(State,
  1423. EscapedSymbols,
  1424. /*CallEvent*/ 0,
  1425. PSK_EscapeOnBind);
  1426. return State;
  1427. }
  1428. ProgramStateRef
  1429. ExprEngine::processPointerEscapedOnInvalidateRegions(ProgramStateRef State,
  1430. const InvalidatedSymbols *Invalidated,
  1431. ArrayRef<const MemRegion *> ExplicitRegions,
  1432. ArrayRef<const MemRegion *> Regions,
  1433. const CallEvent *Call) {
  1434. if (!Invalidated || Invalidated->empty())
  1435. return State;
  1436. if (!Call)
  1437. return getCheckerManager().runCheckersForPointerEscape(State,
  1438. *Invalidated,
  1439. 0,
  1440. PSK_EscapeOther);
  1441. // If the symbols were invalidated by a call, we want to find out which ones
  1442. // were invalidated directly due to being arguments to the call.
  1443. InvalidatedSymbols SymbolsDirectlyInvalidated;
  1444. for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
  1445. E = ExplicitRegions.end(); I != E; ++I) {
  1446. if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>())
  1447. SymbolsDirectlyInvalidated.insert(R->getSymbol());
  1448. }
  1449. InvalidatedSymbols SymbolsIndirectlyInvalidated;
  1450. for (InvalidatedSymbols::const_iterator I=Invalidated->begin(),
  1451. E = Invalidated->end(); I!=E; ++I) {
  1452. SymbolRef sym = *I;
  1453. if (SymbolsDirectlyInvalidated.count(sym))
  1454. continue;
  1455. SymbolsIndirectlyInvalidated.insert(sym);
  1456. }
  1457. if (!SymbolsDirectlyInvalidated.empty())
  1458. State = getCheckerManager().runCheckersForPointerEscape(State,
  1459. SymbolsDirectlyInvalidated, Call, PSK_DirectEscapeOnCall);
  1460. // Notify about the symbols that get indirectly invalidated by the call.
  1461. if (!SymbolsIndirectlyInvalidated.empty())
  1462. State = getCheckerManager().runCheckersForPointerEscape(State,
  1463. SymbolsIndirectlyInvalidated, Call, PSK_IndirectEscapeOnCall);
  1464. return State;
  1465. }
  1466. /// evalBind - Handle the semantics of binding a value to a specific location.
  1467. /// This method is used by evalStore and (soon) VisitDeclStmt, and others.
  1468. void ExprEngine::evalBind(ExplodedNodeSet &Dst, const Stmt *StoreE,
  1469. ExplodedNode *Pred,
  1470. SVal location, SVal Val,
  1471. bool atDeclInit, const ProgramPoint *PP) {
  1472. const LocationContext *LC = Pred->getLocationContext();
  1473. PostStmt PS(StoreE, LC);
  1474. if (!PP)
  1475. PP = &PS;
  1476. // Do a previsit of the bind.
  1477. ExplodedNodeSet CheckedSet;
  1478. getCheckerManager().runCheckersForBind(CheckedSet, Pred, location, Val,
  1479. StoreE, *this, *PP);
  1480. StmtNodeBuilder Bldr(CheckedSet, Dst, *currBldrCtx);
  1481. // If the location is not a 'Loc', it will already be handled by
  1482. // the checkers. There is nothing left to do.
  1483. if (!isa<Loc>(location)) {
  1484. const ProgramPoint L = PostStore(StoreE, LC, /*Loc*/0, /*tag*/0);
  1485. ProgramStateRef state = Pred->getState();
  1486. state = processPointerEscapedOnBind(state, location, Val);
  1487. Bldr.generateNode(L, state, Pred);
  1488. return;
  1489. }
  1490. for (ExplodedNodeSet::iterator I = CheckedSet.begin(), E = CheckedSet.end();
  1491. I!=E; ++I) {
  1492. ExplodedNode *PredI = *I;
  1493. ProgramStateRef state = PredI->getState();
  1494. state = processPointerEscapedOnBind(state, location, Val);
  1495. // When binding the value, pass on the hint that this is a initialization.
  1496. // For initializations, we do not need to inform clients of region
  1497. // changes.
  1498. state = state->bindLoc(cast<Loc>(location),
  1499. Val, /* notifyChanges = */ !atDeclInit);
  1500. const MemRegion *LocReg = 0;
  1501. if (loc::MemRegionVal *LocRegVal = dyn_cast<loc::MemRegionVal>(&location)) {
  1502. LocReg = LocRegVal->getRegion();
  1503. }
  1504. const ProgramPoint L = PostStore(StoreE, LC, LocReg, 0);
  1505. Bldr.generateNode(L, state, PredI);
  1506. }
  1507. }
  1508. /// evalStore - Handle the semantics of a store via an assignment.
  1509. /// @param Dst The node set to store generated state nodes
  1510. /// @param AssignE The assignment expression if the store happens in an
  1511. /// assignment.
  1512. /// @param LocationE The location expression that is stored to.
  1513. /// @param state The current simulation state
  1514. /// @param location The location to store the value
  1515. /// @param Val The value to be stored
  1516. void ExprEngine::evalStore(ExplodedNodeSet &Dst, const Expr *AssignE,
  1517. const Expr *LocationE,
  1518. ExplodedNode *Pred,
  1519. ProgramStateRef state, SVal location, SVal Val,
  1520. const ProgramPointTag *tag) {
  1521. // Proceed with the store. We use AssignE as the anchor for the PostStore
  1522. // ProgramPoint if it is non-NULL, and LocationE otherwise.
  1523. const Expr *StoreE = AssignE ? AssignE : LocationE;
  1524. // Evaluate the location (checks for bad dereferences).
  1525. ExplodedNodeSet Tmp;
  1526. evalLocation(Tmp, AssignE, LocationE, Pred, state, location, tag, false);
  1527. if (Tmp.empty())
  1528. return;
  1529. if (location.isUndef())
  1530. return;
  1531. for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI)
  1532. evalBind(Dst, StoreE, *NI, location, Val, false);
  1533. }
  1534. void ExprEngine::evalLoad(ExplodedNodeSet &Dst,
  1535. const Expr *NodeEx,
  1536. const Expr *BoundEx,
  1537. ExplodedNode *Pred,
  1538. ProgramStateRef state,
  1539. SVal location,
  1540. const ProgramPointTag *tag,
  1541. QualType LoadTy)
  1542. {
  1543. assert(!isa<NonLoc>(location) && "location cannot be a NonLoc.");
  1544. // Are we loading from a region? This actually results in two loads; one
  1545. // to fetch the address of the referenced value and one to fetch the
  1546. // referenced value.
  1547. if (const TypedValueRegion *TR =
  1548. dyn_cast_or_null<TypedValueRegion>(location.getAsRegion())) {
  1549. QualType ValTy = TR->getValueType();
  1550. if (const ReferenceType *RT = ValTy->getAs<ReferenceType>()) {
  1551. static SimpleProgramPointTag
  1552. loadReferenceTag("ExprEngine : Load Reference");
  1553. ExplodedNodeSet Tmp;
  1554. evalLoadCommon(Tmp, NodeEx, BoundEx, Pred, state,
  1555. location, &loadReferenceTag,
  1556. getContext().getPointerType(RT->getPointeeType()));
  1557. // Perform the load from the referenced value.
  1558. for (ExplodedNodeSet::iterator I=Tmp.begin(), E=Tmp.end() ; I!=E; ++I) {
  1559. state = (*I)->getState();
  1560. location = state->getSVal(BoundEx, (*I)->getLocationContext());
  1561. evalLoadCommon(Dst, NodeEx, BoundEx, *I, state, location, tag, LoadTy);
  1562. }
  1563. return;
  1564. }
  1565. }
  1566. evalLoadCommon(Dst, NodeEx, BoundEx, Pred, state, location, tag, LoadTy);
  1567. }
  1568. void ExprEngine::evalLoadCommon(ExplodedNodeSet &Dst,
  1569. const Expr *NodeEx,
  1570. const Expr *BoundEx,
  1571. ExplodedNode *Pred,
  1572. ProgramStateRef state,
  1573. SVal location,
  1574. const ProgramPointTag *tag,
  1575. QualType LoadTy) {
  1576. assert(NodeEx);
  1577. assert(BoundEx);
  1578. // Evaluate the location (checks for bad dereferences).
  1579. ExplodedNodeSet Tmp;
  1580. evalLocation(Tmp, NodeEx, BoundEx, Pred, state, location, tag, true);
  1581. if (Tmp.empty())
  1582. return;
  1583. StmtNodeBuilder Bldr(Tmp, Dst, *currBldrCtx);
  1584. if (location.isUndef())
  1585. return;
  1586. // Proceed with the load.
  1587. for (ExplodedNodeSet::iterator NI=Tmp.begin(), NE=Tmp.end(); NI!=NE; ++NI) {
  1588. state = (*NI)->getState();
  1589. const LocationContext *LCtx = (*NI)->getLocationContext();
  1590. SVal V = UnknownVal();
  1591. if (location.isValid()) {
  1592. if (LoadTy.isNull())
  1593. LoadTy = BoundEx->getType();
  1594. V = state->getSVal(cast<Loc>(location), LoadTy);
  1595. }
  1596. Bldr.generateNode(NodeEx, *NI, state->BindExpr(BoundEx, LCtx, V), tag,
  1597. ProgramPoint::PostLoadKind);
  1598. }
  1599. }
  1600. void ExprEngine::evalLocation(ExplodedNodeSet &Dst,
  1601. const Stmt *NodeEx,
  1602. const Stmt *BoundEx,
  1603. ExplodedNode *Pred,
  1604. ProgramStateRef state,
  1605. SVal location,
  1606. const ProgramPointTag *tag,
  1607. bool isLoad) {
  1608. StmtNodeBuilder BldrTop(Pred, Dst, *currBldrCtx);
  1609. // Early checks for performance reason.
  1610. if (location.isUnknown()) {
  1611. return;
  1612. }
  1613. ExplodedNodeSet Src;
  1614. BldrTop.takeNodes(Pred);
  1615. StmtNodeBuilder Bldr(Pred, Src, *currBldrCtx);
  1616. if (Pred->getState() != state) {
  1617. // Associate this new state with an ExplodedNode.
  1618. // FIXME: If I pass null tag, the graph is incorrect, e.g for
  1619. // int *p;
  1620. // p = 0;
  1621. // *p = 0xDEADBEEF;
  1622. // "p = 0" is not noted as "Null pointer value stored to 'p'" but
  1623. // instead "int *p" is noted as
  1624. // "Variable 'p' initialized to a null pointer value"
  1625. static SimpleProgramPointTag tag("ExprEngine: Location");
  1626. Bldr.generateNode(NodeEx, Pred, state, &tag);
  1627. }
  1628. ExplodedNodeSet Tmp;
  1629. getCheckerManager().runCheckersForLocation(Tmp, Src, location, isLoad,
  1630. NodeEx, BoundEx, *this);
  1631. BldrTop.addNodes(Tmp);
  1632. }
  1633. std::pair<const ProgramPointTag *, const ProgramPointTag*>
  1634. ExprEngine::geteagerlyAssumeBinOpBifurcationTags() {
  1635. static SimpleProgramPointTag
  1636. eagerlyAssumeBinOpBifurcationTrue("ExprEngine : Eagerly Assume True"),
  1637. eagerlyAssumeBinOpBifurcationFalse("ExprEngine : Eagerly Assume False");
  1638. return std::make_pair(&eagerlyAssumeBinOpBifurcationTrue,
  1639. &eagerlyAssumeBinOpBifurcationFalse);
  1640. }
  1641. void ExprEngine::evalEagerlyAssumeBinOpBifurcation(ExplodedNodeSet &Dst,
  1642. ExplodedNodeSet &Src,
  1643. const Expr *Ex) {
  1644. StmtNodeBuilder Bldr(Src, Dst, *currBldrCtx);
  1645. for (ExplodedNodeSet::iterator I=Src.begin(), E=Src.end(); I!=E; ++I) {
  1646. ExplodedNode *Pred = *I;
  1647. // Test if the previous node was as the same expression. This can happen
  1648. // when the expression fails to evaluate to anything meaningful and
  1649. // (as an optimization) we don't generate a node.
  1650. ProgramPoint P = Pred->getLocation();
  1651. if (!isa<PostStmt>(P) || cast<PostStmt>(P).getStmt() != Ex) {
  1652. continue;
  1653. }
  1654. ProgramStateRef state = Pred->getState();
  1655. SVal V = state->getSVal(Ex, Pred->getLocationContext());
  1656. nonloc::SymbolVal *SEV = dyn_cast<nonloc::SymbolVal>(&V);
  1657. if (SEV && SEV->isExpression()) {
  1658. const std::pair<const ProgramPointTag *, const ProgramPointTag*> &tags =
  1659. geteagerlyAssumeBinOpBifurcationTags();
  1660. ProgramStateRef StateTrue, StateFalse;
  1661. tie(StateTrue, StateFalse) = state->assume(*SEV);
  1662. // First assume that the condition is true.
  1663. if (StateTrue) {
  1664. SVal Val = svalBuilder.makeIntVal(1U, Ex->getType());
  1665. StateTrue = StateTrue->BindExpr(Ex, Pred->getLocationContext(), Val);
  1666. Bldr.generateNode(Ex, Pred, StateTrue, tags.first);
  1667. }
  1668. // Next, assume that the condition is false.
  1669. if (StateFalse) {
  1670. SVal Val = svalBuilder.makeIntVal(0U, Ex->getType());
  1671. StateFalse = StateFalse->BindExpr(Ex, Pred->getLocationContext(), Val);
  1672. Bldr.generateNode(Ex, Pred, StateFalse, tags.second);
  1673. }
  1674. }
  1675. }
  1676. }
  1677. void ExprEngine::VisitGCCAsmStmt(const GCCAsmStmt *A, ExplodedNode *Pred,
  1678. ExplodedNodeSet &Dst) {
  1679. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  1680. // We have processed both the inputs and the outputs. All of the outputs
  1681. // should evaluate to Locs. Nuke all of their values.
  1682. // FIXME: Some day in the future it would be nice to allow a "plug-in"
  1683. // which interprets the inline asm and stores proper results in the
  1684. // outputs.
  1685. ProgramStateRef state = Pred->getState();
  1686. for (GCCAsmStmt::const_outputs_iterator OI = A->begin_outputs(),
  1687. OE = A->end_outputs(); OI != OE; ++OI) {
  1688. SVal X = state->getSVal(*OI, Pred->getLocationContext());
  1689. assert (!isa<NonLoc>(X)); // Should be an Lval, or unknown, undef.
  1690. if (isa<Loc>(X))
  1691. state = state->bindLoc(cast<Loc>(X), UnknownVal());
  1692. }
  1693. Bldr.generateNode(A, Pred, state);
  1694. }
  1695. void ExprEngine::VisitMSAsmStmt(const MSAsmStmt *A, ExplodedNode *Pred,
  1696. ExplodedNodeSet &Dst) {
  1697. StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
  1698. Bldr.generateNode(A, Pred, Pred->getState());
  1699. }
  1700. //===----------------------------------------------------------------------===//
  1701. // Visualization.
  1702. //===----------------------------------------------------------------------===//
  1703. #ifndef NDEBUG
  1704. static ExprEngine* GraphPrintCheckerState;
  1705. static SourceManager* GraphPrintSourceManager;
  1706. namespace llvm {
  1707. template<>
  1708. struct DOTGraphTraits<ExplodedNode*> :
  1709. public DefaultDOTGraphTraits {
  1710. DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
  1711. // FIXME: Since we do not cache error nodes in ExprEngine now, this does not
  1712. // work.
  1713. static std::string getNodeAttributes(const ExplodedNode *N, void*) {
  1714. #if 0
  1715. // FIXME: Replace with a general scheme to tell if the node is
  1716. // an error node.
  1717. if (GraphPrintCheckerState->isImplicitNullDeref(N) ||
  1718. GraphPrintCheckerState->isExplicitNullDeref(N) ||
  1719. GraphPrintCheckerState->isUndefDeref(N) ||
  1720. GraphPrintCheckerState->isUndefStore(N) ||
  1721. GraphPrintCheckerState->isUndefControlFlow(N) ||
  1722. GraphPrintCheckerState->isUndefResult(N) ||
  1723. GraphPrintCheckerState->isBadCall(N) ||
  1724. GraphPrintCheckerState->isUndefArg(N))
  1725. return "color=\"red\",style=\"filled\"";
  1726. if (GraphPrintCheckerState->isNoReturnCall(N))
  1727. return "color=\"blue\",style=\"filled\"";
  1728. #endif
  1729. return "";
  1730. }
  1731. static void printLocation(raw_ostream &Out, SourceLocation SLoc) {
  1732. if (SLoc.isFileID()) {
  1733. Out << "\\lline="
  1734. << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
  1735. << " col="
  1736. << GraphPrintSourceManager->getExpansionColumnNumber(SLoc)
  1737. << "\\l";
  1738. }
  1739. }
  1740. static std::string getNodeLabel(const ExplodedNode *N, void*){
  1741. std::string sbuf;
  1742. llvm::raw_string_ostream Out(sbuf);
  1743. // Program Location.
  1744. ProgramPoint Loc = N->getLocation();
  1745. switch (Loc.getKind()) {
  1746. case ProgramPoint::BlockEntranceKind: {
  1747. Out << "Block Entrance: B"
  1748. << cast<BlockEntrance>(Loc).getBlock()->getBlockID();
  1749. if (const NamedDecl *ND =
  1750. dyn_cast<NamedDecl>(Loc.getLocationContext()->getDecl())) {
  1751. Out << " (";
  1752. ND->printName(Out);
  1753. Out << ")";
  1754. }
  1755. break;
  1756. }
  1757. case ProgramPoint::BlockExitKind:
  1758. assert (false);
  1759. break;
  1760. case ProgramPoint::CallEnterKind:
  1761. Out << "CallEnter";
  1762. break;
  1763. case ProgramPoint::CallExitBeginKind:
  1764. Out << "CallExitBegin";
  1765. break;
  1766. case ProgramPoint::CallExitEndKind:
  1767. Out << "CallExitEnd";
  1768. break;
  1769. case ProgramPoint::PostStmtPurgeDeadSymbolsKind:
  1770. Out << "PostStmtPurgeDeadSymbols";
  1771. break;
  1772. case ProgramPoint::PreStmtPurgeDeadSymbolsKind:
  1773. Out << "PreStmtPurgeDeadSymbols";
  1774. break;
  1775. case ProgramPoint::EpsilonKind:
  1776. Out << "Epsilon Point";
  1777. break;
  1778. case ProgramPoint::PreImplicitCallKind: {
  1779. ImplicitCallPoint *PC = cast<ImplicitCallPoint>(&Loc);
  1780. Out << "PreCall: ";
  1781. // FIXME: Get proper printing options.
  1782. PC->getDecl()->print(Out, LangOptions());
  1783. printLocation(Out, PC->getLocation());
  1784. break;
  1785. }
  1786. case ProgramPoint::PostImplicitCallKind: {
  1787. ImplicitCallPoint *PC = cast<ImplicitCallPoint>(&Loc);
  1788. Out << "PostCall: ";
  1789. // FIXME: Get proper printing options.
  1790. PC->getDecl()->print(Out, LangOptions());
  1791. printLocation(Out, PC->getLocation());
  1792. break;
  1793. }
  1794. default: {
  1795. if (StmtPoint *L = dyn_cast<StmtPoint>(&Loc)) {
  1796. const Stmt *S = L->getStmt();
  1797. Out << S->getStmtClassName() << ' ' << (const void*) S << ' ';
  1798. LangOptions LO; // FIXME.
  1799. S->printPretty(Out, 0, PrintingPolicy(LO));
  1800. printLocation(Out, S->getLocStart());
  1801. if (isa<PreStmt>(Loc))
  1802. Out << "\\lPreStmt\\l;";
  1803. else if (isa<PostLoad>(Loc))
  1804. Out << "\\lPostLoad\\l;";
  1805. else if (isa<PostStore>(Loc))
  1806. Out << "\\lPostStore\\l";
  1807. else if (isa<PostLValue>(Loc))
  1808. Out << "\\lPostLValue\\l";
  1809. #if 0
  1810. // FIXME: Replace with a general scheme to determine
  1811. // the name of the check.
  1812. if (GraphPrintCheckerState->isImplicitNullDeref(N))
  1813. Out << "\\|Implicit-Null Dereference.\\l";
  1814. else if (GraphPrintCheckerState->isExplicitNullDeref(N))
  1815. Out << "\\|Explicit-Null Dereference.\\l";
  1816. else if (GraphPrintCheckerState->isUndefDeref(N))
  1817. Out << "\\|Dereference of undefialied value.\\l";
  1818. else if (GraphPrintCheckerState->isUndefStore(N))
  1819. Out << "\\|Store to Undefined Loc.";
  1820. else if (GraphPrintCheckerState->isUndefResult(N))
  1821. Out << "\\|Result of operation is undefined.";
  1822. else if (GraphPrintCheckerState->isNoReturnCall(N))
  1823. Out << "\\|Call to function marked \"noreturn\".";
  1824. else if (GraphPrintCheckerState->isBadCall(N))
  1825. Out << "\\|Call to NULL/Undefined.";
  1826. else if (GraphPrintCheckerState->isUndefArg(N))
  1827. Out << "\\|Argument in call is undefined";
  1828. #endif
  1829. break;
  1830. }
  1831. const BlockEdge &E = cast<BlockEdge>(Loc);
  1832. Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B"
  1833. << E.getDst()->getBlockID() << ')';
  1834. if (const Stmt *T = E.getSrc()->getTerminator()) {
  1835. SourceLocation SLoc = T->getLocStart();
  1836. Out << "\\|Terminator: ";
  1837. LangOptions LO; // FIXME.
  1838. E.getSrc()->printTerminator(Out, LO);
  1839. if (SLoc.isFileID()) {
  1840. Out << "\\lline="
  1841. << GraphPrintSourceManager->getExpansionLineNumber(SLoc)
  1842. << " col="
  1843. << GraphPrintSourceManager->getExpansionColumnNumber(SLoc);
  1844. }
  1845. if (isa<SwitchStmt>(T)) {
  1846. const Stmt *Label = E.getDst()->getLabel();
  1847. if (Label) {
  1848. if (const CaseStmt *C = dyn_cast<CaseStmt>(Label)) {
  1849. Out << "\\lcase ";
  1850. LangOptions LO; // FIXME.
  1851. C->getLHS()->printPretty(Out, 0, PrintingPolicy(LO));
  1852. if (const Stmt *RHS = C->getRHS()) {
  1853. Out << " .. ";
  1854. RHS->printPretty(Out, 0, PrintingPolicy(LO));
  1855. }
  1856. Out << ":";
  1857. }
  1858. else {
  1859. assert (isa<DefaultStmt>(Label));
  1860. Out << "\\ldefault:";
  1861. }
  1862. }
  1863. else
  1864. Out << "\\l(implicit) default:";
  1865. }
  1866. else if (isa<IndirectGotoStmt>(T)) {
  1867. // FIXME
  1868. }
  1869. else {
  1870. Out << "\\lCondition: ";
  1871. if (*E.getSrc()->succ_begin() == E.getDst())
  1872. Out << "true";
  1873. else
  1874. Out << "false";
  1875. }
  1876. Out << "\\l";
  1877. }
  1878. #if 0
  1879. // FIXME: Replace with a general scheme to determine
  1880. // the name of the check.
  1881. if (GraphPrintCheckerState->isUndefControlFlow(N)) {
  1882. Out << "\\|Control-flow based on\\lUndefined value.\\l";
  1883. }
  1884. #endif
  1885. }
  1886. }
  1887. ProgramStateRef state = N->getState();
  1888. Out << "\\|StateID: " << (const void*) state.getPtr()
  1889. << " NodeID: " << (const void*) N << "\\|";
  1890. state->printDOT(Out);
  1891. Out << "\\l";
  1892. if (const ProgramPointTag *tag = Loc.getTag()) {
  1893. Out << "\\|Tag: " << tag->getTagDescription();
  1894. Out << "\\l";
  1895. }
  1896. return Out.str();
  1897. }
  1898. };
  1899. } // end llvm namespace
  1900. #endif
  1901. #ifndef NDEBUG
  1902. template <typename ITERATOR>
  1903. ExplodedNode *GetGraphNode(ITERATOR I) { return *I; }
  1904. template <> ExplodedNode*
  1905. GetGraphNode<llvm::DenseMap<ExplodedNode*, Expr*>::iterator>
  1906. (llvm::DenseMap<ExplodedNode*, Expr*>::iterator I) {
  1907. return I->first;
  1908. }
  1909. #endif
  1910. void ExprEngine::ViewGraph(bool trim) {
  1911. #ifndef NDEBUG
  1912. if (trim) {
  1913. std::vector<ExplodedNode*> Src;
  1914. // Flush any outstanding reports to make sure we cover all the nodes.
  1915. // This does not cause them to get displayed.
  1916. for (BugReporter::iterator I=BR.begin(), E=BR.end(); I!=E; ++I)
  1917. const_cast<BugType*>(*I)->FlushReports(BR);
  1918. // Iterate through the reports and get their nodes.
  1919. for (BugReporter::EQClasses_iterator
  1920. EI = BR.EQClasses_begin(), EE = BR.EQClasses_end(); EI != EE; ++EI) {
  1921. ExplodedNode *N = const_cast<ExplodedNode*>(EI->begin()->getErrorNode());
  1922. if (N) Src.push_back(N);
  1923. }
  1924. ViewGraph(&Src[0], &Src[0]+Src.size());
  1925. }
  1926. else {
  1927. GraphPrintCheckerState = this;
  1928. GraphPrintSourceManager = &getContext().getSourceManager();
  1929. llvm::ViewGraph(*G.roots_begin(), "ExprEngine");
  1930. GraphPrintCheckerState = NULL;
  1931. GraphPrintSourceManager = NULL;
  1932. }
  1933. #endif
  1934. }
  1935. void ExprEngine::ViewGraph(ExplodedNode** Beg, ExplodedNode** End) {
  1936. #ifndef NDEBUG
  1937. GraphPrintCheckerState = this;
  1938. GraphPrintSourceManager = &getContext().getSourceManager();
  1939. std::auto_ptr<ExplodedGraph> TrimmedG(G.Trim(Beg, End).first);
  1940. if (!TrimmedG.get())
  1941. llvm::errs() << "warning: Trimmed ExplodedGraph is empty.\n";
  1942. else
  1943. llvm::ViewGraph(*TrimmedG->roots_begin(), "TrimmedExprEngine");
  1944. GraphPrintCheckerState = NULL;
  1945. GraphPrintSourceManager = NULL;
  1946. #endif
  1947. }