ExprEngine.cpp 68 KB

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