ExprEngine.cpp 91 KB

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