ExprEngine.cpp 73 KB

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