ExprEngine.cpp 73 KB

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