ExprEngine.cpp 81 KB

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